Sub topic 10
Under the Hood: Microtasks and Execution Order
This chapter assumes you already know how the event loop runs callbacks, what Promises are, and how await pauses an async function. Here we look at the exact order in which JavaScript runs that queued work. Once you know the rules, you can predict the output of code that mixes await, .then(), and setTimeout.
Two Queues, Not One
The event loop does not keep a single line of waiting callbacks. It keeps two:
| Queue | What goes in it | When it runs |
|---|---|---|
| Task queue (macrotasks) | `setTimeout` and `setInterval` callbacks, I/O events, UI events | One task per turn of the event loop |
| Microtask queue | Promise reactions (`.then`, `.catch`, `.finally`), code after `await`, `queueMicrotask` callbacks | Fully drained after the current task, before the next task starts |
The key rule is that after each task finishes and the call stack is empty, the engine runs every microtask in the queue. That includes microtasks added while the queue is being drained. Only after that does it take the next task.
Where await Fits
When an async function reaches await, it gives control back to its caller. The rest of the function is scheduled as a microtask, which runs once the awaited value settles. That is why code after await runs before any timer, even a timer with a 0 ms delay:
console.log('A');
setTimeout(() => console.log('E'), 0);
(async () => {
console.log('B');
await null;
console.log('D');
})();
console.log('C');
// Output: A, B, C, D, EHere is the walkthrough:
Aprints synchronously.setTimeoutputs a callback in the task queue.- The async function starts running synchronously and prints
B. Code before the firstawaitalways runs right away. await nullsuspends the function and queues its continuation as a microtask.Cprints, and the main script, which is the current task, ends.- The microtask queue drains, so
Dprints. - The next task runs, so
Eprints.
Microtasks Run in Queue Order
Microtasks run first-in, first-out. A chained .then() is queued only when the previous step finishes, so it goes to the back of the line:
console.log('1');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve()
.then(() => console.log('then 1'))
.then(() => console.log('then 2'));
queueMicrotask(() => console.log('microtask'));
console.log('2');
// Output: 1, 2, then 1, microtask, then 2, timeoutThe first .then callback and the queueMicrotask callback are queued during the script. When then 1 runs, it resolves the next Promise in the chain, and that queues then 2 behind microtask.
Why This Matters in Practice
- Order you can predict. State updates made after an
awaithappen before any pending timers or I/O callbacks. - "Async" is not always "later". Code before the first
awaitruns synchronously. A slow loop there blocks the caller. - Exact tick counts vary. Awaiting a native Promise takes one microtask hop in modern engines. Awaiting a thenable or returning a Promise from
.then()can take extra hops. Don't write code that depends on interleaving at that level. Use explicit chaining orawaitwhen order matters.
Exercise
What does this code print, and in what order? async function f() { console.log('f start'); await undefined; console.log('f end'); } console.log('script start'); setTimeout(() => console.log('timeout'), 0); f(); Promise.resolve().then(() => console.log('then')); console.log('script end');
Show answer
script start, f start, script end, f end, then, timeout. Calling f() prints "f start" synchronously, and its await queues the continuation as a microtask. The .then callback is queued after it. When the script ends, the microtasks run in order ("f end", then "then"), and the setTimeout task runs last.
Exercise
A timer is set with setTimeout(fn, 0), and then a Promise chain runs 1,000 .then() steps that each do a little synchronous work. Does fn run before the chain finishes? Why?
Show answer
No. Each .then step queues the next one as a microtask, and the event loop drains the whole microtask queue before it takes the next task. The timer callback is a task, so it runs only after all 1,000 steps finish.