Chaining .then() Calls
You'll learn how to link multiple asynchronous operations together in a clean, readable sequence.
The Core Idea
Every time you call .then() on a Promise, that call returns a brand new Promise. This new Promise represents the result of whatever you return inside your .then() callback. Because .then() gives you back a Promise, you can immediately call .then() again on it, creating a chain.
Think of it like a relay race: each runner (.then()) passes the baton (the value) to the next runner, who's already waiting and ready to continue.
How It Works
When you return a value from a .then() callback:
- If you return a normal value, the next
.then()receives that value wrapped in a resolved Promise - If you return another Promise, the next
.then()waits for that Promise to settle first
fetch('/user/1')
.then(response => response.json()) // Returns a Promise
.then(user => fetch(`/posts/${user.id}`)) // Returns another Promise
.then(response => response.json()) // Returns a Promise
.then(posts => console.log(posts)); // Final result
Each .then() transforms or extends the data, passing it along to the next step. This lets you write sequential async operations without nesting — goodbye callback hell!
The Sequential Flow
Chains execute one after another, not simultaneously. The second .then() won't run until the first completes. The third waits for the second. This makes ordering predictable and debugging manageable.
Key Takeaway: .then() always returns a new Promise, allowing you to chain multiple async operations in a flat, readable sequence rather than nesting callbacks.