Sub topic 9
async/await: Promises with Synchronous-Looking Code
This chapter assumes you can already build promise chains with then, catch and finally, and that you know how a rejection skips forward through a chain to the next catch. You should also be able to run JavaScript in Node.js or a browser console. Everything here builds on those ideas. async and await don't replace promises. They give you a different way to write the same promise-based code.
The Working Model
async and await are two keywords that work together:
- An async function is a function declared with the
asynckeyword. Calling it always returns a promise, whatever the body does. awaitis an operator you can use inside an async function. It pauses that function until a promise settles. If the promise fulfills,awaitgives you its value. If it rejects,awaitthrows the rejection reason as an exception at that line.
Two rules cover most of how async functions behave:
- Returning a value from an async function fulfills its promise with that value. Throwing from it rejects its promise with the thrown error.
await peither evaluates top's fulfillment value or throwsp's rejection reason.
async function getNumber() {
return 42;
}
async function fail() {
throw new Error('bad input');
}
console.log(getNumber() instanceof Promise); // true
getNumber().then((n) => console.log('fulfilled with', n)); // fulfilled with 42
fail().catch((err) => console.log('rejected with', err.message)); // rejected with bad inputgetNumber returns a plain number, but the caller still receives a promise. This is why code that calls an async function must either await the result or attach then.
What await does with non-promise values
await accepts any value. If the value isn't a promise, await wraps it as though you had called Promise.resolve(value) and then waits for that. So await 5 evaluates to 5, but the function still pauses and resumes later as a microtask. This detail matters when you predict execution order, which the next section covers.
Execution Order Inside an Async Function
An async function runs synchronously up to its first await. At that point it returns its pending promise to the caller, and the caller keeps running. The rest of the function resumes later, after the current synchronous code finishes.
async function work() {
console.log('B: inside, before await');
await null;
console.log('D: after await');
}
console.log('A');
work();
console.log('C');
// Output: A, B, C, DA common wrong guess is that B prints after C, as if calling an async function deferred the whole body. It does not. Only the code after the first await is deferred.
Rewriting a Chain with await
Any then chain can be rewritten as a sequence of await statements. Here is the same three-step computation written both ways:
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
function totalWithThen() {
return delay(50, 2)
.then((n) => n * 3)
.then((n) => delay(50, n + 1));
}
async function totalWithAwait() {
const start = await delay(50, 2);
const tripled = start * 3;
const result = await delay(50, tripled + 1);
return result;
}
totalWithThen().then((v) => console.log('then:', v)); // then: 7
totalWithAwait().then((v) => console.log('await:', v)); // await: 7Each then callback becomes the code after an await. Intermediate results become ordinary local variables. With a chain, a value that a later step needs has to be passed along explicitly or kept in an outer variable. With await, every earlier result is still in scope, which matters most when step three needs the results of both step one and step two:
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
async function buildReport() {
const user = await delay(30, { id: 7, name: 'Ada' });
const orders = await delay(30, [{ total: 20 }, { total: 15 }]);
const sum = orders.reduce((acc, o) => acc + o.total, 0);
return `${user.name} (#${user.id}) spent ${sum}`;
}
buildReport().then(console.log); // Ada (#7) spent 35Error Handling with try/catch/finally
Because await throws on rejection, ordinary try/catch/finally handles both synchronous errors and asynchronous rejections in the same block.
| Promise chain | async/await equivalent |
|---|---|
| `.then((v) => ...)` | `const v = await p;` followed by code |
| `.catch((err) => ...)` | `try { ... } catch (err) { ... }` |
| `.finally(() => ...)` | `finally { ... }` |
| Returning a value from `catch` to recover | Returning or assigning in the `catch` block and continuing |
| Rethrowing in `catch` | `throw err;` inside `catch` |
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
async function loadConfig(shouldFail) {
await delay(20);
if (shouldFail) throw new Error('config missing');
return { retries: 3 };
}
async function start(shouldFail) {
let config;
try {
config = await loadConfig(shouldFail);
} catch (err) {
console.log('using defaults because:', err.message);
config = { retries: 1 };
} finally {
console.log('config step finished');
}
return config.retries;
}
start(false).then((r) => console.log('retries:', r));
start(true).then((r) => console.log('retries:', r));
// Both calls log "config step finished".
// The failing call also logs "using defaults because: config missing" and ends with retries: 1.Keep try blocks narrow. If you wrap an entire function body, a typo-induced TypeError gets caught and "recovered" the same way as a network failure, which hides real bugs. Wrap only the awaits whose failures you know how to handle, and let everything else propagate to the caller.
The `return await` Gotcha Inside try
Outside a try block, return await p and return p behave almost the same way. Inside a try block they differ:
async function withoutAwait() {
try {
return Promise.reject(new Error('late failure'));
} catch (err) {
return 'handled';
}
}
async function withAwait() {
try {
return await Promise.reject(new Error('late failure'));
} catch (err) {
return 'handled';
}
}
withoutAwait().catch((err) => console.log('withoutAwait rejected:', err.message));
withAwait().then((v) => console.log('withAwait fulfilled:', v));
// withoutAwait rejected: late failure
// withAwait fulfilled: handledIn withoutAwait, the function hands the rejected promise to its caller and leaves the try block before the rejection is observed, so catch never runs. In withAwait, the rejection is thrown at the await while the function is still inside try. The rule: when you want the local catch or finally to cover the promise being returned, write return await.
Sequential by Default
Each await waits for its promise to settle before the next line runs. Two independent operations awaited one after the other therefore take the sum of their durations:
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
async function sequential() {
const a = await delay(100, 'a');
const b = await delay(100, 'b');
return [a, b]; // about 200 ms
}
async function parallel() {
const [a, b] = await Promise.all([delay(100, 'a'), delay(100, 'b')]);
return [a, b]; // about 100 ms
}
async function main() {
let t = Date.now();
console.log(await sequential(), Date.now() - t, 'ms');
t = Date.now();
console.log(await parallel(), Date.now() - t, 'ms');
}
main().catch(console.error);The operation starts when you call delay, not when you await it. parallel starts both timers before waiting, and Promise.all waits for both. Use sequential awaits only when a step depends on the previous result. The combinators chapter covers when to choose all, allSettled, race or any, and the final chapter covers related loop mistakes.
Where await Is Allowed
- Inside async functions, including async arrow functions (
async () => {}), async methods (async load() {}), and async function expressions. - At the top level of ES modules, meaning
.mjsfiles, files in a package with"type": "module", or<script type="module">in browsers. This is called top-level await. A module that uses it delays any module that imports it until the awaited promise settles. - Not inside a regular function, even one nested in an async function. A callback passed to
forEachormapis a separate function, soawaitthere either causes a syntax error (if the callback isn't async) or pauses only that callback and not the outer function.
// Save as top-level.mjs and run: node top-level.mjs
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
const value = await delay(50, 'ready');
console.log(value); // readyCommon Errors at a Glance
| Symptom | Cause | Fix |
|---|---|---|
| Variable logs as `Promise { <pending> }` | Missing `await` before an async call | Add `await`, or use `then` |
| `SyntaxError: await is only valid in async functions` | `await` used in a non-async function or callback | Mark the function `async`, or restructure |
| `catch` block never runs for a returned promise | `return p` instead of `return await p` inside `try` | Use `return await` |
| Code is slower than expected | Independent awaits run one after another | Start the operations first, then `await Promise.all` |
| Error silently swallowed | Overly broad `try` with an empty or logging-only `catch` | Narrow the `try`, rethrow what you can't handle |
Exercise
Predict the output order of this program: async function f() { console.log('2'); await undefined; console.log('4'); return '5'; } console.log('1'); f().then(console.log); console.log('3');
Show answer
1, 2, 3, 4, 5. The body of f runs synchronously until the await, so "2" prints right after "1". The call returns a pending promise, and "3" prints. Then f resumes as a microtask and prints "4". Its return value fulfills the promise, and the then callback prints "5".
Exercise
Rewrite this chain as an async function with the same behavior, including recovery: function run() { return Promise.resolve(10).then((n) => { if (n > 5) throw new Error('too big'); return n; }).catch(() => 0).then((n) => n + 1); }
Show answer
async function run() { let n; try { n = await Promise.resolve(10); if (n > 5) throw new Error('too big'); } catch { n = 0; } return n + 1; } This resolves to 1. The throw inside try is caught, n becomes 0, and the function returns 0 + 1.
Exercise
A function contains try { return fetchData(); } catch (err) { return null; }, where fetchData is async. Callers report rejections even though the code "catches" them. Why, and what single change fixes it?
Show answer
return fetchData() returns the pending promise and leaves the try block before the promise rejects, so the local catch never sees the rejection, and the caller receives it. Changing the line to return await fetchData(); makes the rejection throw inside the try, so the catch runs and returns null.