Sub topic 10
When Callbacks Run: The Microtask Queue
This chapter assumes you can create promises, attach then handlers, and write async functions. It also assumes you know that setTimeout schedules a callback for later. The goal here is to predict the exact order in which your callbacks run.
The Working Model
JavaScript runs your code on one thread. Three structures decide what runs next:
- The call stack holds the synchronous code that is running right now.
- The task queue (also called the macrotask queue) holds callbacks from timers, I/O and UI events.
setTimeoutputs its callback here. - The microtask queue holds promise reactions, which are the handlers passed to
then,catchandfinally. It also holds code that resumes afterawaitand callbacks passed toqueueMicrotask.
The event loop follows one rule. When the call stack becomes empty, it drains the whole microtask queue, and only then takes the next task from the task queue. Any microtask added while the queue is draining also runs before the next task.
A handler is queued as a microtask once both of these are true: the promise has settled, and the handler is attached. A handler never runs synchronously, even when the promise is already fulfilled.
The Basic Ordering
console.log('1');
setTimeout(() => console.log('4'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('2');
// Output: 1, 2, 3, 4The 1 and 2 logs are synchronous. The then handler goes into the microtask queue and the timer callback goes into the task queue. Once the stack is empty, the microtask runs first, so 3 prints before 4. This happens even though the timer delay is 0.
Microtasks Scheduled by Microtasks
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => {
console.log('micro 1');
Promise.resolve().then(() => console.log('micro 2'));
});
queueMicrotask(() => console.log('micro 3'));
// Output: micro 1, micro 3, micro 2, timeoutAt the start, the microtask queue holds micro 1 and micro 3. Running micro 1 adds micro 2 to the end of the queue, behind micro 3. The timer callback still waits until the microtask queue is completely empty.
await Resumes as a Microtask
async function work() {
console.log('B');
await null;
console.log('D');
}
console.log('A');
work();
console.log('C');
// Output: A, B, C, DAn async function runs synchronously until it reaches its first await. The code after the await is scheduled as a microtask. The caller therefore continues first and logs C.
Common Errors
| Mistake | What actually happens |
|---|---|
| Expecting `setTimeout(fn, 0)` to run before a resolved promise's `then` | The microtask runs first, every time |
| Assuming a handler on an already-fulfilled promise runs immediately | It is queued and runs after the current synchronous code |
| Assuming code after `await` runs before the caller's next line | The caller continues first |
| Assuming each chain runs to completion before the next chain starts | Chains interleave one step at a time, as the second exercise shows |
Exercise
What does this code print, in order? setTimeout(() => console.log('T'), 0); Promise.resolve().then(() => console.log('P')); (async () => { console.log('S'); await undefined; console.log('W'); })(); console.log('E');
Show answer
S, E, P, W, T. 'S' is logged synchronously inside the async function, and 'E' is the last synchronous line. The 'P' handler was queued before the await continuation, so 'P' runs before 'W'. The timer callback 'T' runs last because it is a task.
Exercise
Predict the output: Promise.resolve().then(() => console.log('a1')).then(() => console.log('a2')); Promise.resolve().then(() => console.log('b1')).then(() => console.log('b2'));
Show answer
a1, b1, a2, b2. Only the first handler of each chain is queued at the start. Running a1 fulfills the next promise in its chain, which queues a2 behind b1. Running b1 then queues b2 behind a2.