Sub topic 6
Chaining: Returning Values and Promises from then
This chapter assumes you already know how to create a promise with new Promise or Promise.resolve, and how to attach then, catch and finally handlers to it. You should also be comfortable with arrow functions, including the difference between an expression body (x) => x + 1 and a block body (x) => { return x + 1; }.
The previous chapter treated then as a way to react to a single result. This chapter covers what then itself returns, and how that return value lets you build a sequence of asynchronous steps that reads top to bottom.
then Always Returns a New Promise
Every call to then creates and returns a brand new promise. It does not return the promise you called it on, and it does not return your handler's result directly.
const p1 = Promise.resolve(1);
const p2 = p1.then((n) => n + 1);
console.log(p1 === p2); // false
console.log(p2 instanceof Promise); // true
p2.then((n) => console.log(n)); // 2The new promise p2 starts out pending. It settles only after p1 has settled and the handler has run. The handler's outcome decides how p2 settles. This is the core rule of chaining: the promise returned by then settles based on what the handler does.
The Settlement Rules
What the handler does decides what happens to the promise that then returned:
| Handler does this | Promise returned by `then` |
|---|---|
| Returns a plain value (number, object, string) | Fulfills with that value |
| Returns nothing (no `return` statement) | Fulfills with `undefined` |
| Returns a promise that later fulfills | Waits, then fulfills with the same value |
| Returns a promise that later rejects | Waits, then rejects with the same reason |
| Throws an error | Rejects with the thrown error |
The last two rows are about errors, and the next chapter covers them in detail. This chapter focuses on the first three: passing values along, and waiting on promises.
Returning a plain value
A plain value goes straight to the next step:
Promise.resolve(2)
.then((n) => n * 3) // returns 6
.then((n) => n + 1) // returns 7
.then((n) => console.log(n)); // 7Each handler gets the value the previous handler returned. The steps run one after another, but each still runs asynchronously. None of them runs until the current synchronous code has finished.
Returning nothing
If a handler has no return, the next step receives undefined:
Promise.resolve('data')
.then((d) => {
console.log('got', d); // got data
})
.then((v) => console.log(v)); // undefinedThis is often fine for a final step that only logs or updates the UI. It becomes a bug when a later step expects a value.
Returning a promise
This is the feature that makes chaining useful for asynchronous work. When a handler returns a promise, the chain waits for that promise before running the next step, and the next step receives its fulfilled value. It does not receive the promise object.
Promise.resolve(2)
.then((n) => n * 3)
.then((n) => new Promise((resolve) => setTimeout(() => resolve(n + 1), 50)))
.then((n) => console.log(n)); // 7, logged after about 50 msThe third handler receives 7, not a Promise. The promise returned by the second then has adopted the inner promise: it stays pending until the inner one settles, then copies its result. You never get a "promise of a promise" this way. Promises flatten automatically.
Flattening Nested Callbacks into a Chain
Adoption is what lets promises fix the "pyramid" shape of nested callbacks. Here are three simulated asynchronous lookups:
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
function getUser(id) {
return delay(50, { id, name: 'Ada' });
}
function getOrders(user) {
return delay(50, [
{ id: 1, userId: user.id, total: 30 },
{ id: 2, userId: user.id, total: 12 },
]);
}
function getTotal(orders) {
return delay(50, orders.reduce((sum, o) => sum + o.total, 0));
}
// Nested: works, but rebuilds the callback pyramid
getUser(7).then((user) => {
getOrders(user).then((orders) => {
getTotal(orders).then((total) => {
console.log('nested total:', total); // nested total: 42
});
});
});
// Flat: each step returns a promise, the chain waits on it
getUser(7)
.then((user) => getOrders(user))
.then((orders) => getTotal(orders))
.then((total) => console.log('flat total:', total)); // flat total: 42Both versions print 42. The flat version has two advantages beyond readability:
- The outer chain knows when the whole sequence is done, because each step's promise feeds the next. In the nested version, the promise returned by the outer
thenfulfills withundefinedalmost immediately, long before the total is computed. - A single
catchat the end of the flat chain sees a failure from any step. The nested version would need a handler at every level.
Because each handler only passes its argument to a function, you can shorten the flat chain further:
getUser(7)
.then(getOrders)
.then(getTotal)
.then((total) => console.log(total)); // 42This works because then calls the handler with one argument, the fulfilled value. Be careful with functions that accept optional extra parameters, since passing a function reference only works cleanly when the function expects exactly that one value.
The Forgotten return
The most common chaining bug is starting a promise inside a handler without returning it:
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
Promise.resolve()
.then(() => {
delay(100, 'late').then((v) => console.log('inner:', v));
// no return: the chain does not wait
})
.then((v) => console.log('next step got:', v));
// next step got: undefined
// inner: lateThe inner promise still runs, but nothing connects it to the chain. The next step runs at once with undefined. Any rejection from the inner promise would also go unnoticed by a catch further down the chain. The fix is one word:
Promise.resolve()
.then(() => {
return delay(100, 'late');
})
.then((v) => console.log('next step got:', v)); // next step got: lateCarrying Earlier Values Forward
Each step only receives the previous step's value. Sometimes a later step needs something from two steps back, such as both the user and their orders. There are three common ways to handle this.
Return an object that bundles the values. Nest one level so the inner handler can see both variables through its closure, then return them together:
getUser(7)
.then((user) => getOrders(user).then((orders) => ({ user, orders })))
.then(({ user, orders }) => {
console.log(`${user.name} has ${orders.length} orders`); // Ada has 2 orders
});One level of nesting used on purpose is fine. The inner chain is still returned, so the outer chain still waits on it.
Store the value in an outer variable. This works, but it adds mutable state shared between steps and is easy to get wrong when the chain is reused:
let savedUser;
getUser(7)
.then((user) => {
savedUser = user;
return getOrders(user);
})
.then((orders) => console.log(savedUser.name, orders.length)); // Ada 2Use async/await. Local variables stay in scope across every await, which removes the problem entirely. A later chapter covers this approach.
Pass-Through When a Handler Is Missing
If then receives something that is not a function, it ignores it. The value passes through unchanged to the next step:
Promise.resolve('kept')
.then(null)
.then(42) // not a function: ignored
.then((v) => console.log(v)); // keptThe same rule explains why catch placed in the middle of a chain does not disturb a successful value. catch(fn) is shorthand for then(undefined, fn), so a fulfilled value passes straight through it. The next chapter builds on this when it follows rejections through a chain.
Chaining Versus Branching
Since every then returns a new promise, calling then twice on the same promise creates two independent branches. It does not create a sequence:
const base = Promise.resolve(10);
base.then((n) => n * 2).then((n) => console.log('chain:', n));
base.then((n) => console.log('branch:', n));
// branch: 10
// chain: 20Both branches receive 10 from base. The chain step receives 20 only because it is attached to the promise returned by n * 2. The output order comes from the extra step in the chain: branch runs in the same round as n * 2, and chain runs one round later. The microtask chapter explains this scheduling exactly.
Branching is useful when several independent consumers need the same result, such as caching one fetch for several callers. When you want steps to run in order, keep attaching each then to the promise the previous then returned.
Exercise
What does this log, and why? Promise.resolve(5).then((n) => { n * 2 }).then((n) => console.log(n));
Show answer
It logs undefined. The braces turn the arrow function's body into a block, and the block has no return statement, so the first then-promise fulfills with undefined. Writing (n) => n * 2 or adding return makes it log 10.
Exercise
Using the delay helper from this chapter, what value is logged and roughly how long does it take? Promise.resolve(1).then((n) => delay(100, n + 1)).then((n) => delay(100, n * 10)).then((n) => console.log(n));
Show answer
It logs 20 after about 200 ms. The first handler returns a promise that fulfills with 2 after 100 ms. The chain waits on it, then the second handler returns a promise that fulfills with 20 after another 100 ms. Each returned promise is adopted, so the steps run in sequence.
Exercise
A teammate writes getUser(7).then((user) => { getOrders(user); }).then((orders) => console.log(orders.length)); and it throws "Cannot read properties of undefined". Explain the bug and give a fixed version that also logs the user's name.
Show answer
The first handler does not return the promise from getOrders, so the next step runs immediately with undefined. One fix: getUser(7).then((user) => getOrders(user).then((orders) => ({ user, orders }))).then(({ user, orders }) => console.log(user.name, orders.length)); Returning the inner chain makes the outer chain wait, and returning the object carries both values forward.