0

I am taking this free course that about JavaScript Promises. In lesson 7, here is the video, there is a code snippet :

new Promise(function(resolve) {
  console.log('first');
  resolve();
  console.log('second');
}).then(function() {
  console.log('third');
});

When I run this code in console it returns:

->first

->second

->third

As far as I know, when we call the resolve, the then method should be run at that moment. So I expect:

->first

->third

So as far as I know, when we call the resolve it should jump to the then method and "console.log("second")" statement shouldn't have been executed.

Can somebody explain how promises behave after encountered with resolve method?

Muhammed Ozdogan
  • 5,341
  • 8
  • 32
  • 53
  • `As far as I know` - you're wrong .- refer to the documentation for [promise then method](https://promisesaplus.com/#the-then-method) - also, `resolve` isn't `return` - so regardless of anything else, the `second` console.log will of course occur – Jaromanda X Aug 08 '18 at 21:45
  • 1
    "resolve, the then method should be run at that moment." - that's simply not true, in the sense of the `then` handler being executed. `then` will **always** at least wait until the current execution stack is empty, before executing the handler. See the [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#Return_value) – ASDFGerte Aug 08 '18 at 21:46
  • Thanks ASDFGerte, as far as I understand "calling resolve" is only indicate that "then method argument" will be executed after the last statement in constructor, if there is no any execution error in promise constructor. – Muhammed Ozdogan Aug 08 '18 at 21:57
  • 1
    What i think actually happens is, that not even `then` is run before the console log of "second". `resolve` will only change the promise to a resolved state, and enqueue potential follow ups (none at this point). Afterwards, `then` is called on the already resolved promise, but will still wait until the current execution stack is empty, before executing the handler. – ASDFGerte Aug 08 '18 at 22:01

0 Answers0