Sub topic 10
Under the Hood: Microtasks and Execution Order
Earlier chapters described what await does: it pauses the async function until a Promise settles, and the rest of the program keeps running. This chapter explains how that works. You will see where the paused code waits, when it runs again, and why await continuations always run before a setTimeout(..., 0) callback.
This chapter assumes you have read the earlier chapters on the event loop, Promises, and await. It also assumes you can run scripts in Node.js or a browser console. All examples run in either one unless the text says otherwise.
Two Queues
The event loop takes waiting work from two kinds of queue.
- A task (also called a macrotask) is a unit of work that the host environment schedules. Examples are a
setTimeoutcallback, a click handler, a network or file I/O callback, and the initial run of a script. - A microtask is a smaller unit of work that the JavaScript engine schedules. Promise reactions (callbacks passed to
then,catch, andfinally), callbacks passed toqueueMicrotask, and the continuation of an async function afterawaitare all microtasks.
The rule that decides execution order is short:
- Take one task from the task queue and run it to completion.
- Run every microtask in the microtask queue, including any microtasks that are added while the queue is being drained.
- In a browser, render if a frame is due.
- Go back to step 1.
Microtasks therefore run as soon as the current synchronous code finishes, and the whole microtask queue empties before the next task can start.
What await Actually Schedules
An async function runs synchronously until it reaches its first await. At that point:
- The awaited value is converted to a Promise. A plain value such as
nullbecomes an already-fulfilled Promise. - The engine registers the rest of the function as a reaction on that Promise.
- The function returns control to its caller. On the first
await, the caller receives the function's pending Promise. - When the awaited Promise settles, the continuation goes into the microtask queue. If the Promise has already settled, the continuation is queued straight away.
So await never resumes synchronously, even when the value is already available. await null still gives up control and lets the current synchronous code finish first.
Predicting Output Order
The next script mixes all of these mechanisms. Read it and predict the output before you run it.
console.log('sync start');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('then callback'));
queueMicrotask(() => console.log('queueMicrotask'));
async function run() {
console.log('async body before await');
await undefined;
console.log('async body after await');
}
run();
console.log('sync end');Output:
sync start
async body before await
sync end
then callback
queueMicrotask
async body after await
timeoutHere is the trace, step by step:
- The script itself is a task, so all of its synchronous lines run first.
sync startprints. setTimeoutputs its callback in the task queue.Promise.resolve()is already fulfilled, so thethencallback goes straight into the microtask queue. The queue is now[then].queueMicrotaskadds its callback:[then, qm].run()executes synchronously up to theawait, soasync body before awaitprints. The continuation is queued:[then, qm, run-continuation].sync endprints, and the script task is finished.- The engine drains the microtask queue in FIFO (first in, first out) order.
- Only after that does the timer task run.
Microtasks run in the order they were queued, not in the order they appear in the source. The await continuation comes last here because it was queued last.
Interleaving Async Functions
Each await is a point where another piece of code can run. When two async functions run at the same time, their microtasks alternate.
async function worker(name) {
for (let i = 1; i <= 3; i++) {
console.log(name, i);
await null;
}
}
worker('A');
worker('B');
console.log('both started');Output:
A 1
B 1
both started
A 2
B 2
A 3
B 3worker('A') prints A 1 and queues its continuation. worker('B') does the same. Each continuation prints one line and queues the next, so the two functions take turns. The same thing happens in real code. Between any two awaits, other code may run and change shared state. Do not assume a variable you read before an await still has the same value after it.
Microtasks Can Starve Tasks
The event loop drains the microtask queue completely before it starts the next task, and that includes microtasks added during the drain. A long chain of microtasks therefore delays every timer, I/O callback, and (in browsers) every repaint.
setTimeout(() => console.log('timeout finally runs'), 0);
let count = 0;
function spin() {
count++;
if (count < 100000) {
queueMicrotask(spin);
} else {
console.log('microtasks done:', count);
}
}
queueMicrotask(spin);Output:
microtasks done: 100000
timeout finally runsThe timeout was scheduled first, yet it waits for all 100,000 microtasks. If you removed the stopping condition, the timer would never fire and a browser tab would freeze. A recursive setTimeout loop does not have this problem. Each step is a separate task, so other tasks and rendering can happen between steps.
Extra Ticks: Returning a Promise from an Async Function
When an async function returns a plain value, its Promise fulfills immediately. When it returns a Promise, the engine has to adopt that Promise's state, and the specification spends extra microtask turns doing so.
async function returnsValue() {
return 1;
}
async function returnsPromise() {
return Promise.resolve(2);
}
returnsPromise().then(v => console.log('promise', v));
returnsValue().then(v => console.log('value', v));
Promise.resolve()
.then(() => console.log('tick 1'))
.then(() => console.log('tick 2'))
.then(() => console.log('tick 3'));Output in current Node.js and browsers:
value 1
tick 1
tick 2
promise 2
tick 3returnsPromise() was called first, but its result arrives two microtask turns later than returnsValue(). Resolving a Promise with another Promise queues one job that calls the inner Promise's then, and that call queues a second job, which finally fulfills the outer Promise.
These timing details are useful when you need to explain a puzzling log. Your code should not rely on them. If two operations must happen in a particular order, make that order explicit with await or then. Do not count ticks.
Node.js Adds More Queues
Node.js keeps its own queues alongside the standard ones.
| Mechanism | Queue | When it runs |
|---|---|---|
| Synchronous code | none | Immediately |
| `process.nextTick(fn)` | Node's next-tick queue | Before promise microtasks, after the current operation |
| `then`, `await`, `queueMicrotask` | Microtask queue | After the next-tick queue, before the next task |
| `setTimeout(fn, 0)` | Timers phase | Next loop iteration, once at least ~1 ms has passed |
| `setImmediate(fn)` | Check phase | After the I/O poll phase of the current iteration |
// Save as order.cjs and run with: node order.cjs
setTimeout(() => console.log('setTimeout'), 0);
setImmediate(() => console.log('setImmediate'));
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
console.log('sync');In a CommonJS file this prints sync, nextTick, promise, and then setTimeout and setImmediate. Those last two can appear in either order when they are scheduled from the main script. Inside an I/O callback, setImmediate always runs first.
Practical Takeaways
- Code after
awaitalways runs later, as a microtask, even when the awaited value is already available. - All pending microtasks run before any timer, I/O callback, or render.
- Microtasks run in the order they were queued.
- Every
awaitlets other code run. Re-check shared state after it. - Long or endless chains of microtasks starve the task queue. Yield with a timer when you need to give the rest of the program a turn.
- Exact tick counts are implementation detail. Express required ordering explicitly in your code.
Exercise
Predict the output of this script and explain why d prints last.
console.log('a');
setTimeout(() => console.log('b'), 0);
(async () => {
console.log('c');
await new Promise(r => setTimeout(r, 0));
console.log('d');
})();
Promise.resolve().then(() => console.log('e'));
console.log('f');
Show answer
The output is a, c, f, e, b, d. The lines a, c, and f are synchronous. e is a microtask, so it runs once the script task ends. The awaited Promise resolves only when its own timer fires. That timer was scheduled after the timer that prints b, so b's task runs first. When the second timer task calls r, the async function's continuation is queued as a microtask and runs at the end of that task, printing d.
Exercise
A developer replaces a recursive setTimeout polling loop with a recursive queueMicrotask loop "to make it faster", and the browser tab stops responding. Explain the cause and give a fix.
Show answer
The event loop drains the whole microtask queue, including newly added microtasks, before it runs another task or renders. A microtask that keeps queueing itself never lets the queue empty, so timers, input events, and painting never get a turn. The fix is to schedule each step as a task again (setTimeout, or a MessageChannel message). An alternative is to keep a microtask loop but stop it after a bounded number of steps and then yield with await new Promise(r => setTimeout(r, 0)).
Exercise
Two async functions run at the same time. Both read a shared counter, await a fetch, and then write counter + 1 back. Starting from 0, the final value is sometimes 1 instead of 2. Why, given that JavaScript is single-threaded?
Show answer
Each await splits the function, and other microtasks and tasks can run between the read and the write. Both functions can read 0 before either one resumes, and then both write 1. To fix it, read and update the shared state after the await in a single synchronous step (for example, counter++ after the fetch completes), or serialize the operations by awaiting one before starting the other.