Sub topic 6
Chaining: Returning Values and Promises from then
This chapter assumes you already know how to create a promise and how to attach a handler with then. It also assumes you are comfortable with arrow functions and setTimeout. Here you will learn the rule that turns single handlers into multi-step pipelines: every call to then returns a new promise, and what your handler returns decides how that new promise settles.
The core rule
When you write p.then(handler), JavaScript creates a fresh promise, which we'll call p2. Once p fulfills, handler runs, and its outcome settles p2:
| Handler does this | `p2` becomes |
|---|---|
| Returns a plain value, like `42` | Fulfilled with `42` |
| Returns nothing | Fulfilled with `undefined` |
| Returns a promise | Settles the same way that promise settles, once it does |
| Throws an error | Rejected with that error |
Because p2 is itself a promise, you can call then on it too. That is a chain. Each step receives whatever the previous step produced.
Passing values and waiting on promises
Promise.resolve(2)
.then((n) => n * 3)
.then((n) => new Promise((resolve) => setTimeout(() => resolve(n + 1), 50)))
.then((n) => console.log(n)); // 7Step by step:
- The chain starts with a promise fulfilled with
2. - The first handler returns
6, a plain value, so the next promise fulfills with6right away. - The second handler returns a promise that fulfills with
7after 50 ms. The chain waits for it. The next handler does not receive the promise object. It receives7. - The last handler logs
7.
This unwrapping is what makes chains useful. A step can do synchronous work or start more asynchronous work, and the following step reads the result the same way in both cases.
Flat chains instead of nested ones
Since returned promises are adopted, you never need to nest then inside then. Compare these two versions:
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
// Nested: works, but rebuilds the callback pyramid
delay(50, 'user')
.then((user) => {
return delay(50, `${user}:orders`).then((orders) => {
console.log('nested:', orders);
});
});
// Flat: return the promise and handle it at the next step
delay(50, 'user')
.then((user) => delay(50, `${user}:orders`))
.then((orders) => console.log('flat:', orders));Both log user:orders. The flat version reads top to bottom, and a single error handler at the end can cover every step. The next chapter covers how that works.
Nesting is still useful when a later step needs a value from an earlier one. You can also carry values forward by returning an object, for example .then((user) => delay(50, 'orders').then((orders) => ({ user, orders }))).
The forgotten return
The most common chaining bug is a handler that starts async work but does not return it.
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
Promise.resolve()
.then(() => {
delay(100, 'saved'); // no return!
})
.then((result) => console.log(result)); // undefined, logged immediatelyThe handler returns undefined, so the next step runs at once and gets nothing. The delayed promise keeps running with no connection to the chain. If it rejected, nothing downstream would see the error.
Exercises
Exercise
What does this log, and why? Promise.resolve(1).then((n) => { n + 1; }).then((n) => console.log(n));
Show answer
It logs undefined. The block body of the first handler computes n + 1 but never returns it, so the promise returned by the first then fulfills with undefined.
Exercise
A handler returns delay(200, 'x'), where delay returns a promise. What does the next then handler receive, and when does it run?
Show answer
It receives the string 'x', not a promise. It runs after about 200 ms, because the promise returned by then adopts the state of the returned promise and waits for it to fulfill.