Await and Rejected Promises
You'll learn how await handles promises that reject and how to catch those errors properly.
How Await Handles Rejection
When you use await on a promise that rejects, await doesn't return a value—it throws the rejection reason as if it were a synchronous error. This is powerful because it lets you handle async errors using the same familiar try/catch syntax you already know from synchronous code.
Think of it like this: if a promise is like ordering food delivery, a rejection is when the delivery fails. With await, instead of getting a special "failed delivery" object, the driver literally throws the problem at your door—and you need to catch it or it'll break your window!
Catching Rejected Promises
async function fetchUser(id) {
try {
const user = await getUserFromAPI(id); // Might reject
console.log('User:', user);
return user;
} catch (error) {
console.log('Failed to fetch user:', error.message);
return null; // Handle gracefully
}
}
If getUserFromAPI() rejects, the await throws that rejection, jumping straight to the catch block.
Without Try/Catch
If you don't catch the error, it propagates out of your async function as a rejected promise:
async function riskyOperation() {
const result = await somethingThatRejects(); // Throws!
// This line never runs
}
// The function returns a rejected promise
riskyOperation().catch(err => console.log('Caught outside:', err));
Key Takeaway: When an awaited promise rejects, await throws the rejection reason, which you should catch with try/catch to handle errors gracefully in async functions.