You can see from below the body is executed immediately just by putting synchronous code in the body rather than asynchronous:
function doSomethingAsynchronous() {
return new Promise((resolve) => {
console.log("a");
resolve("promise result");
});
}
doSomethingAsynchronous();console.log("b");
The result shows the promise body is executed immediately (before 'b' is printed):
a
b
The result of the Promise is retained, to be released to a 'then' call for example:
doSomethingAsynchronous().then(function(pr){console.log("c:"+pr);});console.log("b");
Result:
a
b
c:promise result
Same deal with asynchronous code in the body except the indeterminate delay before the promise is fulfilled and 'then' can be called (point 'c'). So 'a' and 'b' would be printed as soon as doSomethingAsynchronous()
returns but 'c' appears only when the promise is fulfilled ('resolve' is called).
What looks odd on the surface, once the call to 'then' is added, is that 'b' is printed before 'c' even when everything is synchronous. Surely 'a' would print, then 'c' and finally 'b'? The reason why 'a', 'b' and 'c' are printed in that order is because no matter whether code in the body is async or sync, the 'then' method is always called asynchronously by the Promise.
In my mind, I imagine the 'then' method being invoked by something like setTimeout(function(){then(pr);},0);
in the Promise once 'resolve' is called. I.e. the current execution path must complete before the function passed to 'then' will be executed.
Not obvious from the Promise specification why it does this. My guess is it ensures consistent behaviour regarding when 'then' is called (always after current execution thread finishes) which is presumably to allow multiple Promises
to be stacked/chained together before kicking off all the then
calls in succession.
Promise(executor)
-> Step 9.then()
handlers are attached.