Catching Multiple Awaits in One Block
What you'll learn: How to handle errors from several sequential await statements using a single try/catch block.
The Core Idea
When you have multiple await statements inside an async function, you don't need a separate try/catch for each one. A single try block can wrap all of them, and your catch will intercept the first error that occurs from any of those awaits.
Think of it like a safety net beneath a tightrope walker performing several tricks in sequence. One net catches any fall, no matter which trick went wrong.
How It Works
async function fetchUserData(userId) {
try {
const user = await getUser(userId);
const profile = await getProfile(user.profileId);
const posts = await getPosts(user.id);
return { user, profile, posts };
} catch (error) {
console.error('Failed to fetch user data:', error);
return null;
}
}
In this example, if any of the three await calls rejects, execution immediately jumps to the catch block. You don't need three separate error handlers.
Why This Matters
This pattern keeps your code clean when multiple operations should fail together. If fetching the user fails, there's no point trying to fetch their profile or posts—the whole operation should abort. One catch handles all three potential failure points.
The error you receive in catch will be from whichever await rejected first. Subsequent awaits never execute once an error is thrown.
Key Takeaway: A single try/catch block can protect multiple sequential await statements, catching the first rejection from any of them and keeping your error handling concise.