Using .catch() in the Middle of Chains
You'll learn how placing .catch() in the middle of a promise chain allows you to recover from errors and continue processing.
The Core Idea
So far, you've seen .catch() at the end of chains to handle any errors. But you can also place .catch() in the middle of a chain. When an error occurs before that .catch(), it handles the error and can return a value that allows the chain to continue successfully.
Think of it like a safety net on a trapeze act: if the performer falls (an error), they land in the net (the .catch()), bounce back up (return a recovery value), and the show continues.
How It Works
fetchUserData(userId)
.then(user => user.preferences)
.catch(error => {
console.log('User fetch failed, using defaults');
return { theme: 'light', language: 'en' }; // Recovery value
})
.then(preferences => {
console.log('Applying preferences:', preferences);
return applyPreferences(preferences);
})
.then(result => console.log('Success:', result));
If fetchUserData or the first .then() throws an error, the .catch() handles it and returns a default preferences object. The chain continues with that default value, as if nothing went wrong.
Why This Matters
Without a middle .catch(), any error would skip all remaining .then() handlers and go straight to the final error handler (or remain unhandled). By catching and recovering early, you can provide fallback values, retry logic, or partial success scenarios.
The chain only stays "rejected" if your .catch() itself throws or returns a rejected promise.
Key Takeaway: Placing .catch() in the middle of a promise chain lets you handle specific errors, provide fallback values, and allow subsequent operations to continue successfully.