Sub topic 3
Chaining Promises with then, catch, and finally
This chapter assumes you know what a Promise is, the three states it can be in (pending, fulfilled, rejected), and how to create one with new Promise((resolve, reject) => ...). It also assumes you are comfortable with arrow functions and basic try/catch. Here you will learn how then, catch, and finally link Promises into a sequence, how values and errors move along that sequence, and the mistakes that break it.
Async functions and await, covered in later chapters, are built on these same rules. Once you know how a chain behaves, it becomes much easier to predict what awaited code will do.
Every then Returns a New Promise
The rule that makes chaining work is simple: then does not change the Promise you call it on. It creates and returns a new Promise, and the handler you pass to then decides how that new Promise settles.
const p1 = Promise.resolve(1);
const p2 = p1.then(x => x + 1);
console.log(p1 === p2); // false
p2.then(x => console.log(x)); // 2p2 is a separate Promise. It stays pending until p1 fulfills and the handler x => x + 1 has run. Then it fulfills with the handler's return value. Because p2 is a Promise, you can call then on it too. A chain is just this step repeated.
What the handler returns decides the next step
The return value of a handler controls the Promise that then returned:
| Handler does this | Promise returned by `then` |
|---|---|
| Returns a plain value (number, object, `undefined`) | Fulfills with that value |
| Returns a Promise (or any thenable) | Follows it and settles the same way, with the same value or reason |
| Throws an error | Rejects with the thrown error |
| Returns nothing | Fulfills with `undefined` |
The second row is the important one. When a handler returns a Promise, the chain waits for it. This is what lets you run asynchronous steps one after another without nesting.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
delay(100, 2)
.then(n => n * 10) // plain value: next step gets 20 right away
.then(n => delay(500, n + 1)) // Promise: next step waits 500 ms, then gets 21
.then(n => {
console.log(n); // 21
});A thenable is any object with a then method. Promises adopt thenables the same way they adopt real Promises, which is how Promise libraries from different sources can work together.
How Values and Errors Flow Through a Chain
A chain has two tracks. Fulfilled values travel down the success track and are passed to then handlers. Rejections travel down the failure track and skip every then handler until a rejection handler takes them.
Promise.resolve(1)
.then(n => {
throw new Error(`boom at ${n}`);
})
.then(() => {
console.log('skipped'); // never runs
})
.catch(err => {
console.log('caught:', err.message);
return 'recovered';
})
.then(value => {
console.log('after catch:', value);
});
// caught: boom at 1
// after catch: recoveredA thrown error inside a handler works like a call to reject. The second then has no rejection handler, so its returned Promise rejects with the same error and passes it on. The catch handles the error, and because the handler returned normally, the Promise that catch returned fulfills. The chain is back on the success track.
catch: Handling and Recovering
promise.catch(onRejected) is shorthand for promise.then(undefined, onRejected). It follows the same return-value rules as then:
- Return a value from
catchand the chain recovers with that value. - Throw (or rethrow) from
catchand the chain stays rejected. - Return a rejected Promise from
catchand the chain stays rejected.
Recovering is useful when you have a sensible fallback. If you only want to log the error, rethrow it so later code does not treat the failure as success:
function loadConfig() {
return Promise.reject(new Error('config file missing'));
}
loadConfig()
.catch(err => {
console.error('loadConfig failed:', err.message);
throw err; // keep the chain rejected
})
.then(config => console.log('using', config)) // skipped
.catch(err => console.log('final handler:', err.message));If the first catch did not rethrow, the next then would run with config set to undefined. This mistake is easy to miss because nothing crashes.
then(onFulfilled, onRejected) is not the same as then().catch()
then takes an optional second argument, a rejection handler. That handler only covers rejections from the Promise before it. It does not catch errors thrown by the first argument of the same then.
const failInHandler = () => {
throw new Error('thrown inside onFulfilled');
};
Promise.resolve('ok')
.then(failInHandler, err => console.log('not reached:', err.message))
.catch(err => console.log('catch saw:', err.message));
// catch saw: thrown inside onFulfilledBoth handlers are attached to the same Promise, so only one of them can run. Use a separate .catch() when you want to cover errors from the success handler as well. Use the two-argument form only when you deliberately want to handle one step's failure differently from failures in its handler.
Placement matters
A catch handles rejections from everything above it in the chain. A catch in the middle covers the steps before it, and the steps after it are unprotected. The usual pattern is one catch at the end of a chain, with extra catch calls in the middle only where a specific step has a fallback.
finally: Cleanup Without Changing the Result
finally(onFinally) runs its handler when the Promise settles, whether it fulfilled or rejected. It is meant for cleanup such as hiding a loading spinner or closing a connection. It differs from then and catch in three ways:
- The handler receives no arguments. It cannot tell whether the chain succeeded.
- Returning a value does not change the result. The original value or reason passes through.
- Throwing, or returning a Promise that rejects, does replace the result with the new rejection.
Promise.resolve('data')
.finally(() => {
console.log('cleanup 1');
return 'ignored';
})
.then(value => console.log('value:', value)); // value: data
Promise.reject(new Error('original'))
.finally(() => console.log('cleanup 2'))
.catch(err => console.log('reason:', err.message)); // reason: original
Promise.resolve('data')
.finally(() => {
throw new Error('cleanup failed');
})
.catch(err => console.log('reason:', err.message)); // reason: cleanup failedIf the finally handler returns a Promise, the chain waits for it before passing the original result on. This lets cleanup be asynchronous, for example finally(() => db.close()).
Flattening Instead of Nesting
Because returned Promises are adopted, you rarely need to nest then calls. Compare the two shapes using simulated data functions:
const users = { 1: { id: 1, name: 'Ada' } };
const postsByUser = { 1: ['Notes on the Analytical Engine'] };
function getUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
users[id] ? resolve(users[id]) : reject(new Error(`No user ${id}`));
}, 50);
});
}
function getPosts(user) {
return new Promise(resolve => {
setTimeout(() => resolve(postsByUser[user.id] || []), 50);
});
}
// Nested: works, but drifts right and needs a catch at each level
getUser(1).then(user => {
getPosts(user).then(posts => {
console.log('nested:', user.name, posts.length);
});
});
// Flat: each step returns a Promise, one catch covers everything
getUser(1)
.then(user => getPosts(user))
.then(posts => console.log('flat:', posts.length))
.catch(err => console.error('failed:', err.message));The nested version has a hidden bug. The outer handler does not return the inner Promise, so an outer catch would never see a failure from getPosts.
When a later step needs an earlier value
The flat chain above lost user: the last step only receives posts. You have two common options. You can return an object that carries both values forward:
getUser(1)
.then(user => getPosts(user).then(posts => ({ user, posts })))
.then(({ user, posts }) => console.log(`${user.name} has ${posts.length} post(s)`))
.catch(err => console.error('failed:', err.message));Or you can nest one level on purpose, making sure to return the inner chain. Both work, and both are clumsy. This is one of the main problems async/await solves, because awaited values are ordinary variables that stay in scope.
The Forgotten return
The most common chaining bug is a handler with a block body ({ ... }) that starts a Promise but does not return it:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
delay(100, 'a')
.then(a => {
delay(100, a + 'b'); // missing return
})
.then(result => console.log(result)); // undefined, printed ~100 ms earlyThe handler returns undefined, so the next step runs immediately with undefined and does not wait. Any rejection from the unreturned Promise is also disconnected from the chain. Fix it with return delay(100, a + 'b'); or with a concise arrow body: .then(a => delay(100, a + 'b')).
Unhandled Rejections
If a chain rejects and nothing handles it, the runtime reports an unhandled rejection. Browsers log it to the console and fire an unhandledrejection event. Node.js, since version 15, terminates the process by default. Every chain you start should end in a catch, or be returned to a caller who will handle it.
process.on('unhandledRejection', reason => {
console.error('Unhandled rejection:', reason.message);
});
Promise.resolve()
.then(() => {
throw new Error('nobody caught me');
}); // no catchThe listener above is Node.js-specific. Use it as a last-resort safety net for logging, not as a replacement for catch.
Summary of the Rules
then,catch, andfinallyeach return a new Promise.- A handler's return value fulfills the next Promise, a returned Promise is waited on, and a throw rejects it.
- Rejections skip
thensuccess handlers until a rejection handler runs. - A
catchthat returns normally recovers the chain. Rethrow to keep it rejected. finallypasses the original result through unless its handler throws or rejects.- Always
returnPromises from handlers, and end every chain with acatch.
Exercise
Predict the output of this code, in order: Promise.resolve(5) .then(n => n * 2) .then(n => { if (n > 5) throw new Error('too big: ' + n); return n; }) .then(n => console.log('A', n)) .catch(err => { console.log('B', err.message); return 0; }) .finally(() => { console.log('C'); return 99; }) .then(n => console.log('D', n));
Show answer
It prints "B too big: 10", then "C", then "D 0". The first then gives 10. The second throws, so the "A" handler is skipped. The catch logs B and recovers with 0. finally logs C, and its return value 99 is ignored, so D receives 0.
Exercise
This code prints "saved: undefined" before the save completes, and a failed save is never reported. Explain why and fix it. function save(record) { return new Promise((resolve, reject) => setTimeout(() => record.id ? resolve(record.id) : reject(new Error('no id')), 100)); } Promise.resolve({ id: 7 }) .then(record => { save(record); }) .then(id => console.log('saved:', id)) .catch(err => console.error('save failed:', err.message));
Show answer
The block-bodied handler calls save but does not return its Promise, so it returns undefined. The next then runs right away with undefined, and a rejection from save is detached from the chain, so catch never sees it. Fix it by returning the Promise: .then(record => { return save(record); }) or .then(record => save(record)). It then prints "saved: 7" after about 100 ms, and a record without an id reaches the catch.
Exercise
Why does the rejection handler in .then(onSuccess, onError) not catch an error thrown by onSuccess, while .then(onSuccess).catch(onError) does?
Show answer
Both handlers in then(onSuccess, onError) are attached to the same Promise, and only one of them runs depending on how that Promise settled. An error thrown in onSuccess rejects the new Promise returned by then, and no handler is attached to that new Promise. With .then(onSuccess).catch(onError), the catch is attached to the Promise returned by then, so it receives errors thrown by onSuccess as well as earlier rejections.