Search code examples
javascriptnode.jspromiseruntimeevent-loop

Javascript promises setTimeout execution


I have been playing with Promises, but I am having trouble understanding what is happening with the following code:

const promise = new Promise((resolve, reject) => {
  console.log('Promise started')
  resolve('Success')
})

setTimeout(() => {
  console.log('Log inside first setTimeout')
}, 0)

promise.then(res => {
  console.log('Promise log after fulfilled ❌')
})

setTimeout(() => {
  console.log('Log inside second setTimeout')
}, 0)

The output is:

Promise started 
Promise log after fulfilled ❌ 
Log inside first setTimeout 
Log inside second setTimeout 

Why not the below output?

Promise started 
Log inside first setTimeout 
Log inside second setTimeout 
Promise log after fulfilled ❌ 

Between setTimeout(fn, 0)fn call and resolve()fn call which will be given priority?

Is it dependent on browser implementation details?


Solution

  • setTimeout is a macro task - these are resolved after micro tasks, which include Promises. The setTimeout is non-blocking, so the code executes (including the .then) before the first setTimeout does, and then the second setTimeout last of all.