Sub topic 9
async/await: Promises with Synchronous-Looking Code
This chapter assumes you can build promise chains with then, and that you know how a thrown error skips ahead to the nearest catch. It also uses Promise.all from the previous chapter. async and await add no new machinery. They are syntax on top of the promises you already know, and every rule from earlier chapters still holds.
The two keywords
An async function always returns a promise. If the function body returns a value, the promise fulfills with that value. If the body throws, the promise rejects with the thrown error.
await can only be used inside an async function, or at the top level of an ES module. It pauses that function until the awaited promise settles. When the promise fulfills, await gives back its value. When it rejects, await throws the rejection reason at that line.
async function getNumber() {
return 42;
}
async function fail() {
throw new Error('bad input');
}
getNumber().then((n) => console.log(n)); // 42
fail().catch((err) => console.log(err.message)); // bad inputgetNumber behaves like () => Promise.resolve(42), and fail behaves like () => Promise.reject(new Error('bad input')).
Rewriting a chain
Below is a chain from an earlier chapter, followed by the same logic written with await:
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
// Chain version
Promise.resolve(2)
.then((n) => n * 3)
.then((n) => delay(50, n + 1))
.then((n) => console.log('chain:', n)); // chain: 7
// async/await version
async function compute() {
let n = await Promise.resolve(2);
n = n * 3;
n = await delay(50, n + 1);
console.log('await:', n); // await: 7
}
compute();Every await marks a point where a then callback would begin. The code after an await runs later as a microtask, exactly like a then callback. The function stops at each await, but the caller does not. compute() returns a pending promise straight away, and the rest of the program keeps running.
Errors with try/catch
A rejected promise throws at the line where it is awaited, so ordinary try/catch/finally blocks do the work of catch and finally handlers:
async function load() {
try {
await Promise.reject(new Error('network down'));
console.log('skipped');
} catch (err) {
console.log('caught:', err.message); // caught: network down
return 'fallback';
} finally {
console.log('cleanup'); // cleanup
}
}
load().then((v) => console.log(v)); // fallbackWhen nothing inside the function catches the error, the error rejects the promise that the function returned. Someone still has to handle that rejection, either the caller or a catch further up.
Sequential versus concurrent awaits
await waits for one promise at a time. When two pieces of work don't depend on each other, start both before you wait:
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'); // starts only after a finishes
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() {
console.time('sequential');
console.log(await sequential());
console.timeEnd('sequential');
console.time('parallel');
console.log(await parallel());
console.timeEnd('parallel');
}
main().catch(console.error);Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Missing `await` | You get a `Promise` object where you expected a value | Add `await` before the call |
| `await` in a non-async function | `SyntaxError` | Mark the enclosing function `async` |
| `await` inside `forEach` | The loop "finishes" before the work does | Use `for...of`, or `Promise.all` with `map` |
| No `try`/`catch` and a caller that never handles the result | Unhandled rejection | Catch inside the function or at the call site |
Exercise
What does this code log, and in what order? async function f() { console.log('A'); await null; console.log('C'); } f(); console.log('B');
Show answer
It logs A, B, C. The body of f runs synchronously up to the first await, which logs A. At the await, f pauses and returns a pending promise, so the caller logs B. The rest of f runs later as a microtask and logs C.
Exercise
Rewrite fetchUser(id).then((u) => fetchPosts(u.id)).catch(() => []) as an async function named postsFor(id).
Show answer
async function postsFor(id) { try { const u = await fetchUser(id); return await fetchPosts(u.id); } catch { return []; } }. The return await is needed so that a rejection from fetchPosts is caught by the catch block.