Sub topic 10
When Callbacks Run: The Microtask Queue
This chapter assumes you can create promises with new Promise, attach handlers with then, catch and finally, and write simple async functions. You should also know that setTimeout schedules a callback for later. The question here is when "later" happens. Promise handlers are always asynchronous. They also run in a specific, predictable order relative to your synchronous code and to timers. Once you know that order, you can read output like 1, 2, 3, 4 and explain where each line comes from.
The Rule: Promise Handlers Never Run Immediately
A then handler on a promise that is already fulfilled still does not run right away. It waits until the code that is currently running has finished.
console.log('1');
setTimeout(() => console.log('4'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('2');
// Output: 1, 2, 3, 4The program runs in this order:
console.log('1')runs synchronously.setTimeouthands its callback to the timer system. The callback becomes a task (also called a macrotask) once the 0 ms delay passes.Promise.resolve()returns a promise that is already fulfilled. Callingthenon it queues the handler as a microtask.console.log('2')runs synchronously.- The script finishes and the call stack is empty. The engine drains the microtask queue, so
'3'prints. - Only after that does the event loop take the next task, the timer, and
'4'prints.
The guarantee that handlers never run synchronously is deliberate. Code after .then(...) always runs before the handler, whether the promise settled a minute ago or has not settled yet, so a handler's timing does not depend on how quickly the promise settled.
Tasks and Microtasks
The event loop manages two kinds of queued work.
| Queue | What puts work there | When it is processed |
|---|---|---|
| Task queue (macrotasks) | `setTimeout`, `setInterval`, I/O callbacks, UI events, `MessageChannel`, `setImmediate` (Node) | One task per loop turn |
| Microtask queue | `then`/`catch`/`finally` handlers, `await` continuations, `queueMicrotask`, `MutationObserver` | Completely drained after each task, before the next task |
The key word is drained. After a task finishes, the engine runs microtasks until the microtask queue is empty. That includes any microtasks queued while it is draining. Then the browser may render, and the loop picks the next task.
Your top-level script counts as the first task. That explains why all synchronous lines print before any promise handler.
The Executor Runs Synchronously
People often get this wrong: the function you pass to new Promise is not deferred. It runs immediately, during the constructor call. Only the reactions to the promise are deferred.
console.log('A');
const p = new Promise((resolve) => {
console.log('B');
resolve('D');
console.log('C'); // still runs: resolve does not stop the executor
});
p.then((v) => console.log(v));
console.log('E');
// Output: A, B, C, E, DCalling resolve('D') settles the promise but does not return from the executor, so 'C' still prints. The then handler is queued as a microtask and runs after 'E'.
Microtasks Queued During Microtasks
When a then handler returns, the promise that then returned settles, and that queues the next handler in the chain. Each step of a chain is therefore its own microtask, queued only when the previous step finishes.
setTimeout(() => console.log('timeout 1'), 0);
Promise.resolve()
.then(() => {
console.log('then 1');
setTimeout(() => console.log('timeout 2'), 0);
})
.then(() => console.log('then 2'));
queueMicrotask(() => console.log('microtask'));
console.log('sync');
// Output:
// sync
// then 1
// microtask
// then 2
// timeout 1
// timeout 2Here is how the microtask queue changes:
| Moment | Microtask queue | Output so far |
|---|---|---|
| End of script | `then 1`, `microtask` | sync |
| After `then 1` runs | `microtask`, `then 2` | sync, then 1 |
| After `microtask` runs | `then 2` | ..., microtask |
| After `then 2` runs | empty | ..., then 2 |
Only when the queue is empty do the timers run, in the order they were scheduled. timeout 2 was scheduled inside a microtask, but it still waits for the next task turn.
How await Fits In
await is built on the same mechanism. When an async function reaches await, it pauses, and its remaining body is queued as a microtask once the awaited value settles. The code before the first await runs synchronously, like a promise executor.
async function f() {
console.log('f start');
await null;
console.log('f after await');
}
console.log('script start');
f();
Promise.resolve().then(() => console.log('then'));
console.log('script end');
// Output:
// script start
// f start
// script end
// f after await
// thenCalling f() prints 'f start' immediately. The await null queues the continuation first, and the then handler is queued after it, so 'f after await' comes before 'then'. Awaiting a value that is not a promise still yields to the microtask queue. await always pauses for at least one microtask.
Returning a Promise from then Costs Extra Ticks
When a handler returns a plain value, the next step is queued right away. When it returns a promise, the outer promise has to adopt the inner one. That adoption takes extra microtask steps: one to call the inner promise's then, and one for that then to fire.
Promise.resolve()
.then(() => Promise.resolve('inner'))
.then((v) => console.log(v));
Promise.resolve()
.then(() => console.log('a'))
.then(() => console.log('b'))
.then(() => console.log('c'));
// Output: a, b, c, innerThe first chain started first but finishes last, because adopting the returned promise takes two extra microtask turns. The specification defines this ordering, and modern engines follow it. You still should not design code around it.
Microtasks Can Starve Everything Else
Because the microtask queue is drained completely before the next task, a microtask that keeps queuing more microtasks blocks timers, I/O and, in browsers, rendering.
setTimeout(() => console.log('timer'), 0);
let n = 0;
function spin() {
if (n++ < 100000) queueMicrotask(spin);
else console.log('microtasks done');
}
spin();
// Output: microtasks done, timerThe timer was ready almost immediately, but it waits for all 100,000 microtasks to run. Remove the limit and the timer never fires: the page freezes even though no single function runs forever. A recursive promise loop such as function loop() { return Promise.resolve().then(loop); } behaves the same way.
When you need to split long work into chunks that let the page respond, yield with a task (setTimeout, MessageChannel, or scheduler.yield() where it is supported), not a microtask.
Node.js: process.nextTick
Node.js has one more queue. Callbacks passed to process.nextTick sit in their own queue, and in a CommonJS script that queue is drained before the promise microtask queue.
// Save as order.js (CommonJS) and run: node order.js
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
console.log('sync');
// Output: sync, nextTick, promiseIn application code, prefer queueMicrotask or promises. They behave the same way in browsers and Node.
Common Errors
- Expecting
thenon a resolved promise to run synchronously. It never does. If you read a variable right after.then(...), the handler has not set it yet. - Assuming the executor is deferred. Heavy synchronous work inside
new Promise(...)blocks the caller just as if you had written it inline. - Using
setTimeout(fn, 0)andPromise.resolve().then(fn)interchangeably. The first waits for the next task, and the browser may render before it runs. The second runs before any rendering or I/O. - Starving the loop with promise recursion. Long-running loops built on microtasks freeze the UI and delay timers.
Exercise
Predict the output of this code: setTimeout(() => console.log('T'), 0); new Promise((r) => { console.log('E'); r(); }).then(() => console.log('P1')).then(() => console.log('P2')); queueMicrotask(() => console.log('Q')); console.log('S');
Show answer
E, S, P1, Q, P2, T. The executor runs synchronously (E), then the rest of the script (S). The microtask queue holds P1 and then Q. Running P1 queues P2 behind Q. The timer task T runs only after the microtask queue is empty.
Exercise
An async function does console.log('x'); await somePromise; console.log('y');. The caller writes fn(); console.log('z');. In what order do x, y and z appear, and why?
Show answer
x, z, y. The body runs synchronously up to the first await, so x prints during the call. await pauses the function and returns control to the caller, which prints z. The continuation that prints y runs later as a microtask, after somePromise settles and the current synchronous code has finished.
Exercise
A browser app processes 50,000 items with function step(i) { if (i < items.length) { work(items[i]); Promise.resolve().then(() => step(i + 1)); } }. The page freezes until processing ends. Explain the cause and give a fix.
Show answer
Every step queues the next one as a microtask, and the event loop drains the whole microtask queue before rendering or handling input. All 50,000 steps therefore run in a single uninterrupted stretch. To fix it, process items in batches and yield with a task between batches, for example by scheduling the next batch with setTimeout(() => step(i + batchSize), 0), or with await scheduler.yield() where it is supported.