Full answer
Work through it in the order the engine does.
Step 1, the synchronous part (the call stack runs until it is empty):
- script start is printed.
- setTimeout registers a timer callback. It will run in the timers phase later.
- a() is called. It prints a start, then calls b(), which prints b and returns a resolved promise. The await then pauses a() and schedules the rest of a() (the line a end) as a microtask. Control returns to the caller.
- Promise.resolve().then(...) schedules the 'promise' callback as a microtask. It was queued after the continuation of a(), so it comes later.
- process.nextTick schedules a callback in the nextTick queue.
- script end is printed.
Step 2, after the current operation finishes:
- Node empties the nextTick queue first: nextTick is printed.
- Then the microtask queue is emptied in order: a end, then promise.
Step 3, the event loop continues and the timers phase runs the timer: timeout.
Rules to remember: code before the first await runs synchronously. await always yields, even for an already resolved promise. nextTick has priority over promise microtasks in CommonJS. Microtasks always finish before the loop moves on to timers.
Common wrong answers put a end before script end, or promise before nextTick.
async function a() {
console.log('a start');
await b();
console.log('a end');
}
async function b() {
console.log('b');
}
console.log('script start');
setTimeout(() => console.log('timeout'), 0);
a();
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
console.log('script end');The snippet is the puzzle itself. The output is the order of the log lines. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): script start a start b script end nextTick a end promise timeout
Key points
- Code before the first await runs synchronously.
- nextTick runs before promise microtasks in CommonJS.
- The continuation after await is a microtask.
- Timers run after the microtask queue is empty.
Common mistakes
- Thinking that await b() makes b run later. The call itself is synchronous.
- Putting 'a end' before 'script end'.
- Treating nextTick and promise callbacks as the same queue.
- Expecting the timer with 0 ms to run before microtasks.
Follow-ups
- What changes if the file is an ES module?
- What changes if b() is not async?
- Where would setImmediate appear in this output?
Tips
- Narrate the call stack in phases.
- State the three queues in priority order.
- Do not guess the order. Say which queue each line goes to.