Output order of sync, microtask, and macrotask
microtask vs macrotask priority.
C runs first synchronously, then B drains from the microtask queue, then A from the macrotask queue.
claiming setTimeout(0) beats the Promise, or that order is random.
WHAT THIS TESTS This classic snippet checks whether you understand execution priority across the call stack, the microtask queue, and the macrotask queue, which is essential for reasoning about async timing bugs.
A GOOD ANSWER COVERS The output is C, then B, then A. Execution starts on the call stack with synchronous code. setTimeout does not run its callback now; it registers A as a macrotask. Promise.resolve().then does not run now either; it registers B as a microtask. console.log('C') executes immediately because it is synchronous, so C prints first. Once the synchronous code finishes and the call stack is empty, the engine fully drains the microtask queue before picking up any macrotask, so B prints next. Only after all microtasks are exhausted does the loop take the next macrotask and print A. The key rule is that microtasks have priority over macrotasks and the entire microtask queue is emptied between macrotasks.
COMMON WRONG ANSWERS Predicting A before B because setTimeout has a zero delay, claiming the order is nondeterministic, or believing setTimeout and Promise callbacks share one queue with equal priority. Another error is thinking the then callback runs synchronously.
LIKELY FOLLOW-UPS Where process.nextTick fits relative to Promise microtasks in Node, what happens with nested microtasks scheduling more microtasks, and how await desugars into then for ordering.
ONE CONCRETE EXAMPLE If you add a second Promise.resolve().then logging D right after the first then, the output becomes C, B, D, A, because both B and D are microtasks drained before the loop ever reaches the setTimeout macrotask A. Even adding more microtasks that themselves schedule microtasks delays A further, since the engine will not advance to a macrotask until the microtask queue is completely empty.
Read the original → javascript.info
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.