Sub topic 11
Predicting Output Order Step by Step
Earlier chapters introduced the call stack, the task queue, the microtask queue, and how promises and async/await schedule work. This chapter puts those pieces together into a repeatable method for predicting what a snippet of mixed asynchronous code prints. It assumes you know closures, callbacks, basic then/catch, and async/await syntax. You should also be able to run code in a browser console or Node.js so you can check your predictions.
The Tracing Method
Guessing output order from intuition fails as soon as code mixes timers, promise chains, and await. The fix is to simulate the engine by hand, writing its state down as you go. Track three things:
- Output: what has been printed so far.
- Microtask queue: promise reactions,
awaitcontinuations, andqueueMicrotaskcallbacks, in FIFO (first in, first out) order. - Task queue: timer callbacks and other macrotasks, also in FIFO order.
Then apply these rules:
- Run the current task (at first, the whole script) top to bottom. Print synchronous logs immediately. When code schedules something, append it to the right queue. Do not run it yet.
- When the call stack empties, drain the microtask queue completely. If a microtask schedules another microtask, append it to the end of the queue. It still runs in this drain.
- Only when the microtask queue is empty, take the first task from the task queue and go back to step 1.
Hold on to one key point. A microtask scheduled during the drain still runs in that same drain, before any task. A task scheduled from anywhere waits behind every task already queued.
A Worked Example
Predict this output before reading the trace:
console.log('1: script start');
setTimeout(() => {
console.log('2: timeout 1');
Promise.resolve().then(() => console.log('3: promise inside timeout'));
}, 0);
setTimeout(() => console.log('4: timeout 2'), 0);
async function work() {
console.log('5: work start');
await null;
console.log('6: work after await');
}
Promise.resolve()
.then(() => console.log('7: then 1'))
.then(() => console.log('8: then 2'));
work();
queueMicrotask(() => console.log('9: queueMicrotask'));
console.log('10: script end');Phase 1: the script runs synchronously
Walk down the script, one statement at a time:
| Step | Action | Output so far | Microtasks | Tasks |
|---|---|---|---|---|
| 1 | Log `1` | 1 | ||
| 2 | First `setTimeout` | 1 | T1 | |
| 3 | Second `setTimeout` | 1 | T1, T2 | |
| 4 | `Promise.resolve().then(...)` | 1 | then1 | T1, T2 |
| 5 | `work()` logs `5`, hits `await` | 1, 5 | then1, workCont | T1, T2 |
| 6 | `queueMicrotask` | 1, 5 | then1, workCont, qm | T1, T2 |
| 7 | Log `10` | 1, 5, 10 | then1, workCont, qm | T1, T2 |
Two details matter here. Only the first .then is queued in step 4. The second .then attaches to a promise that is still pending, so nothing is scheduled for it yet. Also, work() runs synchronously up to its await, which is why 5 prints before 10.
Phase 2: drain the microtask queue
| Step | Run | Output added | Microtasks after |
|---|---|---|---|
| 8 | then1 logs `7` and resolves its promise | 7 | workCont, qm, then2 |
| 9 | workCont logs `6` | 6 | qm, then2 |
| 10 | qm logs `9` | 9 | then2 |
| 11 | then2 logs `8` | 8 | (empty) |
then2 was queued only when then1 finished. That puts it behind workCont and qm, so 8 prints after 6 and 9.
Phase 3: tasks, one at a time
T1 logs 2 and queues a microtask. Before T2 can start, the engine drains that microtask, which logs 3. Then T2 logs 4.
Final output:
1: script start
5: work start
10: script end
7: then 1
6: work after await
9: queueMicrotask
8: then 2
2: timeout 1
3: promise inside timeout
4: timeout 2Counting Microtask Ticks
The order between two independent chains depends on how many microtask "ticks" each step costs. A tick is one trip through the microtask queue. Most steps cost one tick, but some cost more.
Returning a promise from a `then` callback
Promise.resolve()
.then(() => { console.log('a1'); return Promise.resolve(); })
.then(() => console.log('a2'));
Promise.resolve()
.then(() => console.log('b1'))
.then(() => console.log('b2'))
.then(() => console.log('b3'))
.then(() => console.log('b4'));
// Output: a1, b1, b2, b3, a2, b4You might expect a2 to run right after b1. It does not. When a then callback returns a promise (any thenable), the outer promise has to adopt that promise's state, and the adoption takes two extra ticks:
- The engine queues a job that calls
.thenon the returned promise. - That
.thenreaction is itself a microtask, which finally resolves the outer promise. - Only then is
a2queued.
Meanwhile chain B moves forward one step per tick. That is how b2 and b3 get in ahead of a2.
`await` on a native promise
Since ES2019, await somePromise on a native promise costs one tick, the same as await null. Older engines (Node.js 10 and earlier) used three ticks, so older blog posts can show different output for the same code. An async function that returns a promise has the extra-tick cost described above, because the function's result promise must adopt the returned promise.
| Construct | Ticks before the next step is queued |
|---|---|
| `.then` on an already-resolved promise | 1 |
| `await` on a non-promise value | 1 |
| `await` on a native promise (modern engines) | 1 |
| `then` callback returning a promise | 3 (1 + 2 for adoption) |
| `async` function returning a promise | 3 (1 + 2 for adoption) |
Common Tracing Errors
- Treating
setTimeout(fn, 0)as "run next." The callback goes to the back of the task queue, behind every pending microtask and every task already queued. - Forgetting the synchronous part of
asyncfunctions. Everything before the firstawaitruns immediately, inside the caller's stack frame. - Merging task drains. The engine runs one task, then drains all microtasks, then runs the next task. Microtasks queued inside T1 run before T2 starts.
- Assuming different delays sort by number alone.
setTimeout(a, 10)andsetTimeout(b, 0)usually runbfirst. But a timer's task is only queued once its delay has passed, so a long synchronous block can make both timers due at the same moment. Timers with equal delays run in the order they were created. - Mixing up environments. In Node.js,
process.nextTickandsetImmediateadd their own rules. A later chapter covers them. The method in this chapter applies to promises,queueMicrotask, and timers in both browsers and Node.js.
Exercises
Exercise
Predict the output: setTimeout(() => console.log('A'), 0); Promise.resolve().then(() => { console.log('B'); setTimeout(() => console.log('C'), 0); }); (async () => { console.log('D'); await undefined; console.log('E'); })(); console.log('F');
Show answer
D, F, B, E, A, C. The synchronous pass prints D (the async function runs up to its await) and F. Then the microtask queue drains: B runs and queues timer C behind timer A, and E runs as the await continuation. Finally the tasks run in order: A, then C.
Exercise
Predict the output in a modern engine: async function inner() { console.log('inner'); } async function outer() { console.log('outer start'); await inner(); console.log('outer end'); } outer(); Promise.resolve().then(() => console.log('then')); console.log('sync');
Show answer
outer start, inner, sync, outer end, then. Calling outer() logs "outer start" and then calls inner() synchronously, which logs "inner" and returns an already-resolved native promise. Awaiting that promise costs one tick, so the continuation is queued first. The .then reaction is queued after it. "sync" prints, then the microtasks run in FIFO order.
Exercise
In the "a1/b1" example, change the first chain's callback to return a plain value (return 42) instead of Promise.resolve(). What is the new output, and why?
Show answer
a1, b1, a2, b2, b3, b4. A plain return value resolves the outer promise right away, so a2 is queued in the same tick as b2. Without the two extra adoption ticks, the two chains alternate step by step.