Transforming Data Through Chains
You'll learn: How to pass and transform results from one .then() handler to the next, building up computed values step-by-step.
The Core Idea
When you chain .then() calls, each handler receives the return value from the previous handler. This creates a data pipeline where you can progressively transform a value through multiple steps, each focused on one specific transformation.
Think of it like an assembly line: the first worker adds wheels, the second paints the car, the third adds seats. Each step receives what the previous step produced and enhances it further.
How It Works in Promise Chains
Each .then() handler can:
- Receive the resolved value from the previous step
- Transform that value however you need
- Return the new value to the next
.then()in the chain
fetch('/api/user')
.then(response => response.json()) // Extract JSON
.then(user => user.name) // Extract just the name
.then(name => name.toUpperCase()) // Transform to uppercase
.then(upperName => `Hello, ${upperName}!`) // Format as greeting
.then(greeting => console.log(greeting)); // Use the final result
Each step receives exactly what the previous step returned. The data flows through the chain, getting refined at each stage.
Building Up Complex Transformations
This pattern shines when you need to perform multiple operations in sequence:
getUserId()
.then(id => id * 2) // Double the ID
.then(doubled => doubled + 100) // Add offset
.then(adjusted => `user-${adjusted}`) // Format as string
.then(formatted => console.log(formatted));
Each transformation is isolated, testable, and easy to understand on its own.
Key Takeaway: Promise chains let you transform data step-by-step by returning values from each .then(), creating a clear pipeline from raw input to final result.