What happens when I return a promise from a .then
method which is wrapped in another object like:
somepromise
.then((step1Result) => {
return {
'val1' : synchronousCalculation(),
'val2' : asyncCalculation() // << THIS HERE
};
})
.then((result) => {
// PATH2
});
i.e. is PATH2
guaranteed to have a settled promise in result['val2']
?
A simpler situation is always guaranteed as mentioned in this question where the top answer mentions this article:
When you return something from a then() callback, it’s a bit magic. If you return a value, the next then() is called with that value. However, if you return something promise-like, the next then() waits on it, and is only called when that promise settles (succeeds/fails)
Note that I’m avoiding to call await asyncCalculation()
because I cannot turn the whole method into async
, there’s too much that would have to change if I did that.
3
Answers
The same thing as with any other value of a property of that object, it is not treated in any special way.
No, there is no guarantee about that,
result['val2']
holds a promise that could be in any state.What you could do is something like this:
like that:
No, the
Promise
is not guaranteed to be resolved. Supposing thatsynchronousCalculation
andasyncCalculation
both takestep1Result
as the only argument, you could refactor your code like this:When
Promise.then( callback )
‘scallback
returns aPromise
itself, the next chained then will await that promise. So in order to be sure all your values are resolved, you would need to turn your callback async itself.An
async
function basically returns aPromise
that resolves whenever allawait
statements have been resolved. And returning Promises insidethen
will chain them together. Consider this example:You can see that after resolving the first one, the
then
from that promise gets called. Butthen
does not return the same promise:Every time a new Promise is returned than get’s awaited. So internally, you can nest as many promises as you want. If a Promise is returned, the next step in the chain will await it being resolved, if a value is returned, the next step just gets executed with that value.