Sub topic 11
Predicting Output Order Step by Step
This chapter assumes you already know how the call stack, the task queue, and the microtask queue work, and that await resumes its function as a microtask. Here those pieces become a single method you can use to trace any snippet that mixes synchronous code, timers, promises, and async functions.
The Tracing Method
Keep three lists on paper: Output, Microtasks, and Tasks. Then follow these rules:
- Run all synchronous code from top to bottom. Log output as it happens. When code schedules something, add it to the end of the matching queue.
- When the call stack is empty, run microtasks one at a time, from the front, until the queue is empty. This includes any microtasks that get added while you are draining.
- Take one task from the front of the task queue and run it to completion.
- Go back to step 2.
A Worked Trace
console.log('1');
setTimeout(() => {
console.log('2');
Promise.resolve().then(() => console.log('3'));
}, 0);
Promise.resolve().then(() => {
console.log('4');
setTimeout(() => console.log('5'), 0);
});
(async () => {
console.log('6');
await null;
console.log('7');
})();
console.log('8');Here is how the three lists change as you apply the rules:
| Step | What runs | Output so far | Microtasks | Tasks |
|---|---|---|---|---|
| Sync | `log('1')`, schedule timer T2 | 1 | T2 | |
| Sync | `.then` callback queued | 1 | M4 | T2 |
| Sync | async body logs 6, `await` queues continuation | 1 6 | M4, M7 | T2 |
| Sync | `log('8')` | 1 6 8 | M4, M7 | T2 |
| Drain | M4 logs 4, schedules T5 | 1 6 8 4 | M7 | T2, T5 |
| Drain | M7 logs 7 | 1 6 8 4 7 | T2, T5 | |
| Task | T2 logs 2, queues M3 | 1 6 8 4 7 2 | M3 | T5 |
| Drain | M3 logs 3 | 1 6 8 4 7 2 3 | T5 | |
| Task | T5 logs 5 | 1 6 8 4 7 2 3 5 |
Final output: 1 6 8 4 7 2 3 5.
Three points from this trace come up again and again:
- The body of an
asyncfunction runs synchronously up to its firstawait. That is why6prints before8. - Microtasks keep their queue order.
M4was queued beforeM7, so4prints first. - A microtask created inside a task (
M3) runs right after that task finishes and before the next timer (T5).
Common Errors When Tracing
- Forgetting the drain is complete. Microtasks added during draining run in the same drain, before any task.
- Treating
new Promise(executor)as asynchronous. The executor runs synchronously. Only the.thencallbacks are microtasks. - Counting
awaitas a task. Its continuation is a microtask, so it runs before every pending timer.
new Promise((resolve) => {
console.log('executor');
resolve();
}).then(() => console.log('then'));
console.log('after');
// Output: executor, after, thenExercise
Predict the output: setTimeout(() => console.log('a'), 0); Promise.resolve().then(() => { console.log('b'); Promise.resolve().then(() => console.log('c')); }); console.log('d');
Show answer
d, b, c, a. The synchronous log prints d. The microtask drain prints b and queues another microtask, which runs in the same drain and prints c. Only then does the timer task print a.
Exercise
In an async function, code before the first await logs 'x', and code after it logs 'y'. A setTimeout with delay 0 that logs 'z' was scheduled before the function was called. A synchronous log of 'w' comes after the call. What is the order?
Show answer
x, w, y, z. The function body runs synchronously up to the await, then the remaining synchronous code runs. The continuation runs as a microtask, and the timer task runs last.