Returning Promises from .then()
You'll learn how returning a Promise from inside a .then() flattens your chain and waits for that new Promise to settle before continuing.
When you return a value from .then(), the next .then() receives that value. But what if you return a Promise instead? JavaScript does something clever: it unwraps that Promise automatically.
How Promise Flattening Works
If your .then() callback returns a Promise, the chain doesn't continue until that returned Promise settles. Once it resolves, its value flows to the next .then(). If it rejects, the error flows to the next error handler.
This prevents "promise nesting hell"—you don't need to write .then() inside .then(). The chain stays flat and readable.
The Pattern
fetchUser(userId)
.then(user => {
// Return a NEW Promise
return fetchOrders(user.id);
})
.then(orders => {
// This receives the RESULT of fetchOrders, not the Promise
console.log(orders);
});
Here, fetchOrders(user.id) returns a Promise. JavaScript waits for it to resolve, then passes orders to the next .then().
Without Returning the Promise
If you don't return the Promise, the chain continues immediately:
fetchUser(userId)
.then(user => {
fetchOrders(user.id); // Missing 'return'
})
.then(orders => {
console.log(orders); // undefined! The Promise wasn't waited for
});
The second .then() runs before fetchOrders finishes, receiving undefined instead.
Think of It Like a Relay Race
Returning a Promise hands the baton to the next runner only after completing the lap. Without the return, you hand off an empty baton while still running.
Key Takeaway: Always return Promises from .then() callbacks to keep your chain flat and sequential—JavaScript will automatically wait for each Promise to settle before moving to the next step.