4
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

dragonfly
  • 17,407
  • 30
  • 110
  • 219
  • 4
    Because promises are always asynchronous. – dfsq Aug 19 '16 at 16:26
  • Invariant behavior == less hard-to-find bugs. – jib Aug 19 '16 at 23:40
  • 2
    see also [What is the intention behind clause 2.2.4 of Promise/A+ spec?](http://stackoverflow.com/q/36932244/1048572) – Bergi Aug 22 '16 at 13:05
  • Because once you enter the async world there is no way out unless you time travel to the future. I guess you have to study the event queues and job queues of JS. Then it will automatically make sense – Redu Aug 23 '16 at 11:09

2 Answers2

1

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.

Ian
  • 480
  • 5
  • 8
0

Ian's answer focuses on technical implementation - thanks a lot. I want post additional answer that focuses on "why" with respect to the JavaScript concurrency model (I realized it when watching Modern Asynchronous JavaScript on Pluralsight.

So let's imagine piece of code:

let progressStatus;

function opThatReturnsPromise() {
  return Promise.resolve();
}

opThatReturnsPromise().then(function() {
  console.log(progressStatus = "Done");
})

console.log(progressStatus = "In progress...");

If "static" Promises were resolved synchronously, then this piece would result in output:

Done
In progress...

This is because of Run-to-completion. So ensuring asynchronicity, ensures consistent behaviour - no matter what is actually happening in the operation that is encapsulated by the Promise object.

dragonfly
  • 17,407
  • 30
  • 110
  • 219