-2

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?

Pavan Gangireddy
  • 417
  • 1
  • 3
  • 13

2 Answers2

2

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.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • Hi @jack, thanks for the quick reply. The answer is straightforward and understandable. However it would be more useful if you provide reference link to the above mentioned concept. – Pavan Gangireddy May 11 '20 at 08:10
  • @PavanGangireddy please check the answers and comments in the duplicates. There are several blog and video links. – adiga May 11 '20 at 08:12
  • 1
    @PavanGangireddy Here's the solution https://stackoverflow.com/questions/38752620/promise-vs-settimeout (tl;dr - promises are micro tasks, and these are executed before setTimeouts, which are macrotasks. setTimeout also does not block the code execution, so the promise is resolved while waiting for the setTimeout) – Jack Bashford May 11 '20 at 08:13
  • The downvote is mine. There is no such thing as a priority, also there are no "threads" involved. "resolves the promise before returning to see if it's finished or not. " makes no sense to me. – Jonas Wilms May 11 '20 at 08:14
  • @JonasWilms sorry, wrong terminology. I'll edit my post to reflect my comments information – Jack Bashford May 11 '20 at 08:15
  • @JonasWilms Sorry, I had an idea that I'd seen this before - wrong context. My bad, and thank you for your consideration :) – Jack Bashford May 11 '20 at 08:29
2

Promises have a higher priority because they are queued in the micro task queue. Tasks in the micro task queue are handled first. Then the other scheduled tasks, setTimeout in this case, are dealt with.

Tuhin Karmakar
  • 171
  • 2
  • 9