dragonfly dragonfly - 3 months ago 10
Javascript Question

Creating already resolved Promise with static value - why execution is still asynchronous

Promise.resolve("resolved").then(function(result) {
console.log(result)
});
console.log("promise created");


results in:

"promise created"
"resolved"


My question is: why execution is still async? What is happening behind the scenes of a Promise?

If I wrap
console.log
in
setTimeout
with delay
0
, then promise resolution happens before
console.log

Answer

The initial call to Promise.resolve(...) is synchronous, but anything that you chain off of in in a .then() block will always be async due to the event loop implemented under the hood.

Your console.log("promise created"); is called outside of your promise chain and is therefore executed immediately after thee initial Promise.resolve(...) call.

Since your console.log("promise created"); outside of your promise chain, as soon as the initial call to Promise.resolve(...) occurs, the console log is executed.