dragonfly dragonfly - 1 year ago 63
Javascript Question

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

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

results in:

"promise created"

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

If I wrap
with delay
, then promise resolution happens before

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download