Search code examples
javascriptnode.jsasynchronouspromiseevent-loop

microtask vs synchronous code execution order


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')


Solution

  • 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'.