-1

I'm trying to understand the order of execution of javascript asynchronous code in the event loop.

Here's my very short code snippet.

How can we explain the actual order of execution: in promise -> end -> in then? Why does the promise constructor run before the console.log('end')?

const p = new Promise((res, rej) => {
  console.log('in promise')
  res()
})

p.then(() => console.log('in then'))

console.log('end')
Eugene Barsky
  • 5,780
  • 3
  • 17
  • 40
  • We can explain it by saying that `then` callbacks are asynchronous, which you presumably already know if you have heard the terms "microtask" and "event loop". What more information are you looking for? – Bergi Jun 21 '20 at 18:34
  • @Bergi Sorry for a clumsy question. What I cannot understand is why the promise (which is asynchronous) is executed before the final `console.log`, while the `then`-block is executed after it. – Eugene Barsky Jun 21 '20 at 19:04
  • 1
    No. [The `new Promise` constructor is not asynchronous](https://stackoverflow.com/q/59415313/1048572). Only `then` callbacks are asynchronously executed. – Bergi Jun 21 '20 at 20:14

1 Answers1

1

The first thing that runs in the promise constructor, logging out "in promise"

The second thing that runs is p.then, setting up some code to run at a future time.

The thing thing to run is console.log('end');

Your code is now done running, so execution returns to the event loop. A promise is in the resolved state, so microtasks run and the .then callback logs out 'in then'.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98