Real-World Chain Examples
You'll learn: How to apply promise chains to actual patterns you'll encounter daily, like fetching and transforming API data or recovering from errors gracefully.
Common Pattern: Fetch, Parse, Transform
The most frequent real-world chain involves fetching data from an API, parsing the response, and transforming it for your application:
fetch('/api/users/42')
.then(response => response.json())
.then(userData => userData.name.toUpperCase())
.then(upperName => {
console.log('Display name:', upperName);
return upperName;
})
.catch(error => {
console.error('Failed to load user:', error);
return 'Unknown User'; // Provide fallback
});
Each .then() does one job: fetch the resource, extract JSON, transform it, then use it. Errors anywhere in the chain fall through to the single .catch().
Error Recovery Flow
Sometimes you want to recover from a specific failure and continue:
fetch('/api/premium-data')
.catch(error => {
console.warn('Premium failed, trying free tier');
return fetch('/api/free-data'); // Return new promise
})
.then(response => response.json())
.then(data => {
console.log('Got data:', data);
})
.catch(error => {
console.error('Both sources failed:', error);
});
The first .catch() catches the premium API failure and returns a new promise (the free API call). If that succeeds, the chain continues normally. Only if both fail does the final .catch() run.
Think of It Like Assembly Lines
Promise chains mirror factory assembly lines: raw materials (API responses) move through stations (.then() handlers), each adding refinement. If something breaks at any station, the error handler (.catch()) intercepts it and can either fix it or halt production.
Key Takeaway: Real-world promise chains follow predictable patterns—fetch-parse-transform for data retrieval, and try-fallback-catch for error resilience. Each .then() step has one clear responsibility.