0
console.log(1)
setTimeout(()=>console.log(2),0)
Promise.resolve(3).then(console.log)
console.log(4)

consider the above code. Here is what I expect from the code.

  • 1 is logged out, setTimeout is an async function so it gets added to the queue.
  • The promise is resolved inline but after that, whatever is in then acts as async. so it also gets added to the queue.
  • Then 4 is logged out and there is no more inline code left.
  • So, setTimeout will get executed from queue printing 2 and after that 3.
  • therefore the final output should be 1 4 2 3

But the output comes to be 1 4 3 2. can you please explain to me what is actually happening here.

Ashu Sahu
  • 417
  • 6
  • 7
  • 2
    Promises use a microtask queue that is higher priority than the regular task queue – Jaromanda X Jul 02 '21 at 11:17
  • 1
    There are 2 queues involved here: Task and Microtask queue. Callbacks scheduled using promises go into the microtask queue and it will be processed after the script ends. After processing the Microtask queue, the Task queue will be processed. – Yousaf Jul 02 '21 at 11:23
  • have you tried rxjs operators ? – Akshay Rathod Ar Jul 02 '21 at 11:49

1 Answers1

1

it is because promises have their own queue which is like between sync and async operations. Every time promise is resolved or rejected its result gets to the very end of the queue. I would say this example shows the case even clearer:

  console.log(1)
  setTimeout(()=>console.log(2),0)
  Promise.resolve(3).then(console.log).then(()=>console.log("three"))
  Promise.resolve(5).then(console.log).then(()=>console.log("five"))
  console.log(4)

1 and 4 appears one by one as it is sync operations. Then the whole promises queue comes out, adding every new "then" to the end. Finally, we get setTimeout result.

Murat Colyaran
  • 2,075
  • 2
  • 8
  • 27
Tarukami
  • 1,160
  • 5
  • 8