Sub topic 9
async/await Under the Hood
This chapter assumes you know how promises settle and how .then callbacks are queued as microtasks, which the previous chapter covered. You should also be comfortable writing basic async functions. Here you will see what the engine actually does when it meets async and await. Once you have that model, you can predict exactly where an async function pauses, when it resumes, and why some bugs that look like ordinary code are really scheduling bugs.
The Core Model: Pause, Queue, Resume
An async function is a function that always returns a promise and can pause at each await. Pausing does not block the thread. The function hands control back to its caller and asks to be resumed later.
The rules are short:
- Calling an async function runs its body synchronously, right away, on the current call stack.
- At the first
await, the function suspends. Its local variables and position are saved, and the caller continues. - When the awaited value settles, a microtask is queued to resume the function from where it stopped.
- When the body finishes, the promise the function returned is resolved with the return value. If the body throws, that promise is rejected.
A common mistake is to think that await "waits" the way a blocking call in another language does. It does not. The engine runs other code in the meantime: the rest of the caller, other microtasks, and eventually other tasks.
async function task(name) {
console.log(name, 'start');
await null;
console.log(name, 'after first await');
await null;
console.log(name, 'after second await');
}
task('A');
task('B');
console.log('sync done');
// Output:
// A start
// B start
// sync done
// A after first await
// B after first await
// A after second await
// B after second awaitBoth functions run up to their first await during the synchronous phase. After the script finishes, the microtask queue holds "resume A" and then "resume B". Each resumption runs until the next await, which queues another microtask at the back of the queue. As a result, the two functions interleave step by step.
Desugaring await into then
You can roughly rewrite an async function as promise chaining. This is not exactly what the engine does, but it gives the same timing for ordinary cases:
// async version
async function loadTotal() {
const a = await Promise.resolve(2);
const b = await Promise.resolve(3);
return a + b;
}
// approximate promise version
function loadTotalWithThen() {
return Promise.resolve(2).then((a) => {
return Promise.resolve(3).then((b) => {
return a + b;
});
});
}
loadTotal().then((v) => console.log('async:', v));
loadTotalWithThen().then((v) => console.log('then:', v));Each await becomes a .then whose callback holds "the rest of the function". The callback runs as a promise reaction, which means it runs as a microtask. The real implementation uses a suspended generator-like state machine instead of nested closures, so local variables and try blocks keep working across awaits.
What Exactly Gets Awaited
await accepts any value, and how it handles the value affects how many microtask ticks pass before the function resumes.
| Awaited value | What the engine does | Ticks before resuming (if already settled) |
|---|---|---|
| Non-promise (`42`, `null`) | Wraps it in a resolved promise | 1 |
| Native promise | Attaches a reaction to it directly | 1 |
| Thenable (object with a `then` method) | Wraps it in a new promise and calls its `then` in a separate job | More than 1 |
Since ES2019, engines no longer wrap a native promise in an extra promise when you await it. Older engines took three ticks for await nativePromise, so you may find old blog posts that show a different output order. Do not write code whose correctness depends on these exact tick counts. Know that they exist so that surprising traces make sense.
The return-a-promise gotcha
Returning a promise from an async function costs extra ticks. The function's own promise has to adopt the returned promise's state, and the spec does this through an extra job.
async function returnsValue() {
return 1;
}
async function returnsPromise() {
return Promise.resolve(1);
}
returnsPromise().then(() => console.log('returned a promise'));
returnsValue().then(() => console.log('returned a value'));
// Output:
// returned a value
// returned a promisereturnsPromise was called first, yet its .then runs last. Its outer promise needs two extra microtask ticks to adopt the inner promise's state. return await somePromise behaves almost the same as return somePromise in timing, and inside a try block it is the correct choice, as the next section shows.
Errors: Rejections Become Throws
When an awaited promise rejects, the function resumes by throwing the rejection reason at the await. This is why ordinary try/catch works:
function failLater() {
return new Promise((_, reject) => {
setTimeout(() => reject(new Error('network down')), 10);
});
}
async function withAwait() {
try {
return await failLater();
} catch (err) {
return 'recovered: ' + err.message;
}
}
async function withoutAwait() {
try {
return failLater(); // the rejection escapes the try block
} catch (err) {
return 'never reached';
}
}
withAwait().then(console.log); // recovered: network down
withoutAwait().catch((e) => console.log('escaped:', e.message)); // escaped: network downIn withoutAwait, the function returns before the promise rejects, so the try block has already exited. The rejection goes straight to the caller.
Sequential Versus Concurrent Awaits
Each await suspends the function until that one value settles. If you write independent operations one after another, they run one after another:
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function sequential() {
const start = Date.now();
const a = await delay(100, 'a');
const b = await delay(100, 'b');
console.log('sequential', a, b, Date.now() - start, 'ms'); // about 200 ms
}
async function concurrent() {
const start = Date.now();
const [a, b] = await Promise.all([delay(100, 'a'), delay(100, 'b')]);
console.log('concurrent', a, b, Date.now() - start, 'ms'); // about 100 ms
}
sequential().then(concurrent);In concurrent, both timers start right away because both delay calls run before anything is awaited. The host runs the two timers in parallel, and the function awaits just once. Use sequential awaits only when a later step needs an earlier step's result.
Common Errors
Forgetting await
Without await, you get the promise instead of its value. if (isValid(x)) where isValid is async is always truthy, because a promise object is truthy. TypeScript and linters such as ESLint's no-floating-promises rule (from typescript-eslint) catch many of these.
async callbacks inside forEach
forEach calls your callback and throws away the promise it returns. It does not wait for anything:
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
async function broken(items) {
items.forEach(async (item) => {
await delay(10);
console.log('processed', item);
});
console.log('all done?'); // logs first
}
async function fixed(items) {
for (const item of items) {
await delay(10);
console.log('processed', item);
}
console.log('all done'); // logs last
}
broken([1, 2]).then(() => fixed([3, 4]));Use for...of for sequential processing, or await Promise.all(items.map(async ...)) for concurrent processing.
Assuming await yields to rendering or timers
await resumes as a microtask, so it does not give the browser a chance to paint or let a timer fire. A loop with await null inside still holds the page hostage until the loop ends. A later chapter on blocking and starvation returns to this point.
Exercise
Predict the output of this code: async function f() { console.log('f1'); await undefined; console.log('f2'); } console.log('start'); f().then(() => console.log('f done')); Promise.resolve().then(() => console.log('p')); console.log('end');
Show answer
start, f1, end, f2, p, f done. The body of f runs synchronously up to the await, which queues "resume f" first. The Promise.resolve().then callback queues "p" second. Resuming f logs f2 and finishes the body, which resolves f's promise and queues the "f done" reaction behind "p".
Exercise
A teammate writes async function save(user) { try { return db.insert(user); } catch (e) { log(e); return null; } } and notices that insert failures are never logged. Why, and what is the one-word fix?
Show answer
The function returns the pending promise from db.insert immediately, so the try block has already exited when the promise later rejects. The rejection passes to the caller without touching the catch. The fix is to add await (return await db.insert(user)), so that the function suspends inside the try block and the rejection is thrown at the await, where catch can handle it.