Why Try/Catch Works with Async Functions
You'll learn: How async functions transform rejected promises into catchable exceptions.
The Magic Bridge
Remember that await unwraps promise values? It has a secret second job: when a promise rejects, await converts that rejection into a thrown exception. This is why traditional try/catch blocks suddenly work with asynchronous code inside async functions.
Without async/await, rejected promises require .catch() handlers. But async functions give you a different mental model—they let you write asynchronous code that looks synchronous, including error handling.
How the Transformation Works
When you await a promise:
- If the promise resolves: You get the value
- If the promise rejects: An exception is thrown at that line
Since it's a thrown exception, your try/catch block intercepts it just like any synchronous error:
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
const data = await response.json();
return data;
} catch (error) {
// Catches both:
// 1. Rejected promises from fetch
// 2. Errors thrown in response.json()
console.error('Failed to fetch user:', error);
return null;
}
}
The Analogy
Think of await as a translator: promises speak the language of .then() and .catch(), while procedural code speaks try/catch. Await translates rejected promises into thrown exceptions so both worlds can communicate.
Key Takeaway: Async functions convert rejected promises into thrown exceptions when you await them, which is why try/catch blocks can intercept promise rejections in async code.