Reputation: 2998
In the event loop there are:
As I understand it, the microtask queue runs after every phase of the event loop.
The first phase of the event loop is the "timers" phase. See here: https://blog.insiderattack.net/event-loop-and-the-big-picture-nodejs-event-loop-part-1-1cb67a182810
So given this code:
setTimeout(() => console.log('TIMEOUT'));
Promise.resolve().then(() => console.log('PROMISE');
I would expect the logs to read
TIMEOUT
PROMISE
But instead you get
PROMISE
TIMEOUT
I understand that the "PROMISE" log is from a callback in the microtask queue. But the timer phase is the first phase. If in each phase we first run the callback queue and THEN the microtask queue, why am I seeing the timer log after the log in the microtask queue?
Upvotes: 0
Views: 88
Reputation: 350
setTimeout
always runs after the execution of current script
. So even if your Promise and setTimeout has a resolve time of 1s, the promise will be resolved first and only after that, the timeout will be triggered.
Upvotes: 0
Reputation: 137084
Because your code is ran from a task, and that after this initial task, there will already be a microtask checkpoint, just like after every task.
It's not very clear in the diagram, but even if you had 33 timer callbacks firing in the same phase, they would all empty the nextTick
queue and the microtask queue, so there would have been like 33 such checkpoints.
Upvotes: 0