Sub topic 12
try/catch with async and await
This chapter assumes you know JavaScript functions and classes, that you can create and consume basic promises, and that you have read the earlier chapters on try, catch, finally, and promise rejections. Every example runs in Node.js 18 or later, or in a browser console.
An async function lets you write asynchronous code that reads like synchronous code. It also lets you go back to plain try/catch for errors that a callback-based try would miss. This only works if you put await in the right places. Most of the bugs in this chapter come from a missing await.
The working model: await turns a rejection into a throw
An async function always returns a promise. Two rules connect it to ordinary error handling:
- If code inside an
asyncfunction throws, the function's returned promise rejects with that error. - If you
awaita promise that rejects, theawaitexpression throws the rejection reason at that line.
Rule 2 is what makes try/catch work again. While the function is paused at an await, it is still inside the try block. When the promise settles, the function resumes in that same block. A rejection is then thrown at the await, and the surrounding catch receives it.
function fetchScore(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id < 0) reject(new RangeError(`Invalid id ${id}`));
else resolve(id * 10);
}, 50);
});
}
async function showScore(id) {
try {
const score = await fetchScore(id);
console.log('Score:', score);
} catch (err) {
console.error(`${err.name}: ${err.message}`);
}
}
showScore(3); // Score: 30
showScore(-1); // RangeError: Invalid id -1Compare this with the setTimeout example from the earlier chapter. In that example, the try block had already finished when the callback threw. Here, the try block cannot finish until the awaited promise settles.
The catch handled the error, so showScore's own promise fulfills rather than rejects. If the catch block rethrows, the caller receives a rejected promise.
Common error 1: return without await inside try
This is the gotcha you are most likely to meet in practice. return somePromise inside a try hands the promise to the caller and leaves the try block straight away. A rejection that happens later never passes through your catch.
function fetchScore(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id < 0) reject(new RangeError(`Invalid id ${id}`));
else resolve(id * 10);
}, 50);
});
}
async function withoutAwait(id) {
try {
return fetchScore(id);
} catch {
return -1; // never reached for a rejection
}
}
async function withAwait(id) {
try {
return await fetchScore(id);
} catch {
return -1;
}
}
withAwait(-1).then((v) => console.log('withAwait:', v)); // withAwait: -1
withoutAwait(-1).then(
(v) => console.log('withoutAwait:', v),
(err) => console.log('withoutAwait rejected:', err.message)
); // withoutAwait rejected: Invalid id -1Outside a try block, return promise and return await promise behave the same. Inside a try with a catch or finally, they behave differently. Write return await there.
Common error 2: finally runs too early
The same mistake breaks cleanup. A finally block runs when control leaves the try. If the try returns a promise it did not await, control leaves immediately, and you release the resource while the work is still using it.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function withConnection(task, awaitIt) {
const conn = { open: true };
console.log('opened');
try {
return awaitIt ? await task(conn) : task(conn);
} finally {
conn.open = false;
console.log('closed');
}
}
async function query(conn) {
await sleep(20);
console.log('query sees open =', conn.open);
return 'rows';
}
async function main() {
await withConnection(query, false); // opened, closed, query sees open = false
await withConnection(query, true); // opened, query sees open = true, closed
}
main();With await, the finally block waits for the task to settle, whether it fulfills or rejects. A rejection still reaches the caller after cleanup runs, as it does with synchronous finally.
Common error 3: promises you never await
A try block only covers the promises you await inside it. If a promise is started and nobody awaits it (a "floating" promise), its rejection escapes. Node.js 15 and later then crash the process with an unhandled rejection. Browsers log it to the console.
Array.prototype.forEach with an async callback is the classic case. forEach ignores the promises the callback returns:
async function saveScore(id) {
await new Promise((resolve) => setTimeout(resolve, 10));
if (id < 0) throw new RangeError(`Invalid id ${id}`);
return id;
}
async function saveAllBroken(ids) {
try {
ids.forEach(async (id) => {
await saveScore(id); // rejection escapes the try
});
console.log('broken: reported success');
} catch (err) {
console.log('broken: caught', err.message); // never runs
}
}
async function saveAllSequential(ids) {
try {
for (const id of ids) {
await saveScore(id);
}
console.log('sequential: all saved');
} catch (err) {
console.log('sequential: caught', err.message);
}
}
saveAllSequential([1, -2, 3]); // sequential: caught Invalid id -2
// saveAllBroken([1, -2, 3]); // uncomment to see the unhandled rejectionUse for...of with await when the steps must run one after another. When they can run in parallel, use Promise.all as in the next section. Either way, the try then has something to await.
Parallel work: Promise.all and Promise.allSettled
To run several operations at once, start them all and then await a combined promise.
async function saveScore(id) {
await new Promise((resolve) => setTimeout(resolve, 10 * Math.abs(id)));
if (id < 0) throw new RangeError(`Invalid id ${id}`);
return id;
}
async function main() {
try {
const saved = await Promise.all([1, -2, 3, -4].map(saveScore));
console.log('all saved', saved);
} catch (err) {
console.log('Promise.all rejected:', err.message); // Invalid id -2
}
const results = await Promise.allSettled([1, -2, 3, -4].map(saveScore));
for (const r of results) {
if (r.status === 'fulfilled') console.log('ok', r.value);
else console.log('failed', r.reason.message);
}
}
main();Promise.all rejects with the first rejection. The other operations keep running, because a promise cannot be cancelled. Promise.all handles their later rejections internally, so they are not reported as unhandled, but your code never sees them. If you need every outcome, or one failure should not hide the successes, use Promise.allSettled. It never rejects, so you inspect status on each result yourself.
| Situation | Pattern | What the catch receives |
|---|---|---|
| One operation | `try { await op() }` | That operation's error |
| Steps in order | `for...of` with `await` inside `try` | The first failing step; later steps never start |
| Parallel, all must succeed | `await Promise.all(...)` in `try` | The first rejection only |
| Parallel, collect every outcome | `await Promise.allSettled(...)` | Nothing; check each `status` |
| Value with a fallback | `await op().catch(() => fallback)` | Handled inline, no `try` needed |
Mixing await with .catch()
await and .catch() combine well. .catch() returns a new promise that fulfills with the fallback value, so you can recover from one failure without wrapping a whole block:
async function loadSettings() {
throw new Error('settings service down');
}
async function main() {
const settings = await loadSettings().catch((err) => {
console.warn('Using defaults:', err.message);
return { theme: 'light' };
});
console.log(settings.theme); // light
}
main();This works well when a single call has an obvious default. Use try/catch when the recovery spans several statements.
Keep try blocks narrow
A large try around several awaits catches all of them, and then you can't tell which one failed. Wrap only the call you can recover from, or add context and rethrow with the cause option from the earlier chapter:
async function getUser(id) {
if (id === 0) throw new Error('not found');
return { id, name: 'Ada' };
}
async function getOrders(user) {
throw new Error('orders DB timeout');
}
async function buildReport(id) {
const user = await getUser(id); // let this propagate unchanged
let orders;
try {
orders = await getOrders(user);
} catch (err) {
throw new Error(`Could not load orders for user ${id}`, { cause: err });
}
return { user, orders };
}
buildReport(1).catch((err) => {
console.error(err.message); // Could not load orders for user 1
console.error(err.cause.message); // orders DB timeout
});The top of the chain still needs a handler
Every chain of async calls ends at a caller that is not itself awaited: an event listener, a timer, a script's main() call. A rejection that reaches that point is unhandled. Close the chain explicitly:
async function main() {
throw new Error('startup failed');
}
main().catch((err) => {
console.error('Fatal:', err.message);
process.exitCode = 1; // in a browser, report it instead
});In ES modules you can use top-level await and wrap it in try/catch directly. An unhandled rejection from top-level await fails the module. The next chapter covers the global handlers that report anything that still slips through.
Exercise
This function is meant to return null when the lookup fails, but callers still see a rejected promise. Why, and what is the one-word fix? async function find(id) { try { return lookup(id); } catch { return null; } }
Show answer
return lookup(id) hands the pending promise back and leaves the try block at once, so the later rejection never passes through the catch. Change it to return await lookup(id); so the function waits inside the try and the rejection is thrown there and caught.
Exercise
You call await Promise.all([a(), b(), c()]) inside try/catch. Both b() and c() reject. What does the catch receive, and what happens to the other rejection? How would you see both?
Show answer
The catch receives whichever rejection happens first. Promise.all handles the other rejection internally, so it is not reported as unhandled, but your code never sees it, and the remaining operations keep running. To see every failure, use await Promise.allSettled([...]) and check each result's status and reason.
Exercise
In withConnection, why does the version without await print "closed" before the query finishes, even though finally is supposed to run after the try?
Show answer
finally runs when control leaves the try block. Without await, the try block returns the pending promise right away, so control leaves immediately and finally closes the connection while the query is still waiting. With return await, the function stays paused inside try until the task settles, so cleanup happens afterwards.