Sub topic 12
try/catch with async and await
This chapter assumes you know how promises reject and how .catch() handles a rejection. You should also be comfortable writing async functions and using await. The code runs in Node.js 18 or later, or in a browser console.
How await Turns a Rejection into a Throw
When you await a promise that rejects, the rejection reason is thrown at the line with the await. To the surrounding code it looks like a synchronous throw, so an ordinary try/catch can handle it. Inside an async function, await connects the promise world back to normal control flow.
function delay(ms, fail) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (fail) reject(new Error('Network down'));
else resolve({ id: 1, name: 'Ada' });
}, ms);
});
}
async function loadUser(fail) {
try {
const user = await delay(50, fail);
console.log('Loaded', user.name);
return user;
} catch (err) {
console.error('Could not load user:', err.message);
return null;
} finally {
console.log('Request finished');
}
}
loadUser(false).then(() => loadUser(true));The finally block runs whether the awaited promise fulfills or rejects. That makes it the right place to hide spinners, release locks, or close connections in async code.
The Missing await Gotcha
A try block only catches a rejection if the promise is awaited inside it. If you return a promise without awaiting it, the function exits the try block before the promise settles, and the rejection goes to the caller without passing through your catch.
function failLater() {
return Promise.reject(new Error('boom'));
}
async function noAwait() {
try {
return failLater(); // not awaited: catch is skipped
} catch (err) {
return 'recovered';
}
}
async function withAwait() {
try {
return await failLater(); // awaited: catch runs
} catch (err) {
return 'recovered';
}
}
noAwait().catch((err) => console.log('noAwait rejected:', err.message));
withAwait().then((value) => console.log('withAwait:', value));Outside a try block, return await adds nothing. Inside one, it decides whether your handler runs at all.
The same thing happens when you forget await on a call whose result you don't use. Writing saveLog(entry); inside a try starts the work and moves on, so a later rejection becomes an unhandled rejection.
Errors from Parallel Work
Promise.all rejects as soon as any input rejects. If you await it, one try/catch covers the whole group:
async function loadAll() {
try {
const [a, b] = await Promise.all([
Promise.resolve('first'),
Promise.reject(new Error('second failed')),
]);
console.log(a, b);
} catch (err) {
console.error('A task failed:', err.message);
}
}
loadAll();When you need the result of every task, including the ones that failed, use Promise.allSettled. It never rejects. Instead it returns an array of { status, value } or { status, reason } objects that you inspect yourself.
Choosing Between try/catch and .catch()
Both styles handle the same rejections. Pick the one that reads best for the task:
| Situation | Usual choice |
|---|---|
| Several sequential awaits that share one handler | `try/catch` around them |
| You need cleanup after async work | `try/finally` |
| A single call with a fallback value | `await p.catch(() => fallback)` |
| A fire-and-forget call you won't await | Attach `.catch()` directly |
Exercise
An async function contains try { return fetchData(); } catch { return []; }, where fetchData returns a promise that rejects. What does the caller receive, and how do you fix the function so that it returns an empty array?
Show answer
The caller receives a rejected promise, because the promise is returned without being awaited and the catch block never runs. Change the line to return await fetchData(); so the rejection is thrown inside the try block and the catch block returns [].
Exercise
Inside a try block you write await Promise.all([taskA(), taskB()]), and taskB rejects. Does the catch block run? What should you use instead if you need taskA's result even when taskB fails?
Show answer
Yes. Promise.all rejects as soon as taskB rejects, and await throws that reason into the catch block. Use Promise.allSettled instead, then check each result's status to read taskA's value and taskB's reason.