How to block a promise for javascript and return the allowed result?

I obviously misunderstand something about how js promises are allowed or about the semantics of "return".

I am called by a function that expects me to be in sync - to return a value. To calculate this value, some asynchronous code is required (in particular, the ForEach method in the dstore Collection

What I'm trying to accomplish is something like this, but that doesn't work, since the mySynchronousFunction function has no return value.

function mySynchronousFunction() { var accumulator = {}; var myPromise = doAsynchronousThingThatSideEffectsAccumulator(); // Now my caller is expecting the value of accumulator. myPromise.then(function() {return accumulator;}) } 

I understand that JS must allow single-threaded implementations, so it is not recommended to block it, but there should be some template for gluing asynchronous synchronous code that I just missed.

+5
source share
2 answers

You cannot make a synchronous result from an asynchronous operation in Javascript. You just can't do it. If any part of your operation is asynchronous, the whole result should be asynchronous, and you should either use a callback, promise, or some other such mechanism to communicate when the operation is completed, and the result is ready.

If your async operation already returns a promise (what it looks like), you should simply return this from the wrapper function:

 function myWrapperFunction() { var accumulator = {}; var myPromise = doAsynchronousThingThatSideEffectsAccumulator(accumulator); // Now my caller is expecting the value of accumulator. return myPromise.then(function(result) { // operate on the accumulator object using the async result return accumulator; }) } myWrapperFunction.then(function(accumulator) { // write your code here that uses the accumulator result }); 

You may also note that a feature that works with side effects is rarely the best design template. You can also skip the entry and return it through the allowed promises and completely eliminate side effects.

+6
source

No, there is no way to make synchronous asynchronous code. After you make an asynchronous call, you should process the result asynchronously completely.

JavaScript is single-threaded, so if you make a lock loop that waits for the result, then code that takes care of the result will not be able to work.

If you want to return something from an asynchronous function, you must return a promise that the calling code can use to process the result asynchronously.

+3
source

All Articles