Sub topic 5
Reacting to Results with then, catch and finally
A promise holds a result that may not exist yet. To use that result you register handlers, which are functions the promise calls once it settles. This chapter covers the three methods that register handlers: then, catch and finally. It explains what each handler receives, when it runs, and what happens to its return value or a thrown error.
This chapter assumes you know the three promise states (pending, fulfilled, rejected) and can create promises with new Promise, Promise.resolve and Promise.reject. It also assumes you are comfortable with arrow functions and setTimeout. Longer chains and the details of error propagation have their own chapters later. Here the focus is on how a single handler behaves.
The shape of then
then takes up to two arguments:
promise.then(onFulfilled, onRejected);onFulfilled(value)runs if the promise fulfills, and receives the fulfillment value.onRejected(reason)runs if the promise rejects, and receives the rejection reason, which is usually anError.
At most one of the two runs, and it runs at most once. A settled promise never changes state, so a handler can never be called twice or have its result replaced.
function loadUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) resolve({ id, name: 'Ada' });
else reject(new Error(`invalid id ${id}`));
}, 50);
});
}
loadUser(1).then(
(user) => console.log('loaded', user.name), // loaded Ada
(err) => console.log('failed', err.message)
);
loadUser(-1).then(
(user) => console.log('loaded', user.name),
(err) => console.log('failed', err.message) // failed invalid id -1
);Both arguments are optional. If an argument is not a function, then ignores it. In that case the result passes through unchanged to the promise that then returns. This rule is what makes catch possible, as the next sections show.
then always returns a new promise
Every call to then, catch or finally returns a new promise. It does not return the original promise. The new promise settles according to what the handler does:
- If the handler returns a value, the new promise fulfills with that value.
- If the handler throws, the new promise rejects with the thrown error.
- If no handler matched the outcome (for example, a rejection reached a
thenwith noonRejected), the new promise copies the original outcome.
This is the foundation of chaining, which the next chapter covers in full. For now, remember one consequence: a handler's return value matters. Whatever you return becomes the input to the next step.
const original = Promise.resolve(10);
const derived = original.then((n) => n * 2);
console.log(original === derived); // false
derived.then((n) => console.log(n)); // 20Handlers always run asynchronously
A handler never runs during the call to then, even if the promise has already settled. The promise schedules the handler to run after the currently executing synchronous code finishes.
const ready = Promise.resolve('ready');
ready.then((v) => console.log(v));
console.log('sync');
// Output:
// sync
// readyThis guarantee removes a whole class of bugs that callback APIs suffer from. Some callback APIs call their callback immediately in one case and later in another. With promises, the code after .then(...) always runs before the handler, whatever state the promise is in. The chapter on the microtask queue explains exactly where handlers are scheduled relative to timers.
Attaching several handlers to one promise
You can call then on the same promise more than once. Each handler receives the same value, and they run in the order you registered them.
const config = new Promise((resolve) => {
setTimeout(() => resolve({ theme: 'dark' }), 50);
});
config.then((c) => console.log('first sees', c.theme));
config.then((c) => console.log('second sees', c.theme));
// Output:
// first sees dark
// second sees darkThis is different from chaining. Calling config.then(a); config.then(b); gives two independent branches that both read the original value. Writing config.then(a).then(b) makes b receive whatever a returned. Mixing these up is a frequent source of undefined values.
catch is then without a success handler
catch(onRejected) behaves exactly like then(undefined, onRejected). It exists because the intent is clearer to read.
loadUser(-1)
.then((user) => console.log('loaded', user.name))
.catch((err) => console.log('failed', err.message)); // failed invalid id -1Here's what happens step by step:
loadUser(-1)rejects.- The first
thenhas no rejection handler, so its returned promise rejects with the same error. catchreceives that error.
If catch returns normally, the promise it returns fulfills, and the chain continues as if the error was handled. To keep the chain rejected, rethrow the error inside catch.
then(a, b) is not the same as then(a).catch(b)
The two forms differ in one important case. onRejected in then(a, b) only handles rejection of the promise that then was called on. It does not see errors thrown by a, because a and b are siblings. A catch placed after the then sees both.
const handlerBug = (v) => {
throw new Error(`could not process ${v}`);
};
// Form 1: the sibling rejection handler misses the handler's error
Promise.resolve('data')
.then(handlerBug, (err) => console.log('form 1 caught:', err.message))
.catch((err) => console.log('form 1 escaped:', err.message));
// form 1 escaped: could not process data
// Form 2: catch after then sees the handler's error
Promise.resolve('data')
.then(handlerBug)
.catch((err) => console.log('form 2 caught:', err.message));
// form 2 caught: could not process datafinally for cleanup
finally(onFinally) runs its handler whether the promise fulfills or rejects. It is meant for cleanup that should happen either way: hiding a spinner, closing a connection, releasing a lock.
let loading = true;
loadUser(1)
.then((user) => console.log('loaded', user.name))
.catch((err) => console.log('failed', err.message))
.finally(() => {
loading = false;
console.log('loading is now', loading);
});
// Output:
// loaded Ada
// loading is now falsefinally has three rules that differ from then:
- The handler receives no arguments. It cannot tell whether the promise fulfilled or rejected. If you need to know, use
thenorcatchinstead. - The handler's return value is ignored. The promise returned by
finallysettles with the original outcome, so values and errors pass through. - There is one exception to rule 2. If the handler throws or returns a rejected promise, that new rejection replaces the original outcome. If it returns a promise that fulfills,
finallywaits for that promise before passing the original outcome along.
The examples below show each rule. They are separate chains, so run them one at a time to keep the output order clear.
// Rule 2: the return value is ignored and the original value passes through
Promise.resolve('value')
.finally(() => 'ignored')
.then((v) => console.log(v)); // value// Rule 2: the original rejection passes through after cleanup
Promise.reject(new Error('original'))
.finally(() => console.log('cleanup'))
.catch((err) => console.log(err.message));
// cleanup
// original// Rule 3: throwing in finally replaces the outcome
Promise.resolve('value')
.finally(() => {
throw new Error('cleanup failed');
})
.catch((err) => console.log(err.message)); // cleanup failedSummary of handler behavior
| Method | Handler runs when | Handler receives | Handler returns a value | Handler throws |
|---|---|---|---|---|
| `then(f)` | fulfilled | the value | new promise fulfills with it | new promise rejects |
| `then(_, r)` | rejected | the reason | new promise fulfills with it | new promise rejects |
| `catch(r)` | rejected | the reason | new promise fulfills with it | new promise rejects |
| `finally(h)` | either | nothing | ignored, original outcome passes through | new promise rejects with the new error |
Common errors
Calling the handler instead of passing it
const p = new Promise((resolve) => setTimeout(() => resolve('late'), 50));
p.then(console.log('too early')); // logs immediately, then passes undefined
p.then(() => console.log('on time')); // logs after the promise settlesconsole.log('too early') runs at once and returns undefined. then(undefined) is ignored, so no handler is registered. The fix is to pass a function: p.then(() => ...) or p.then(console.log).
Forgetting to return from a handler
Promise.resolve(5)
.then((n) => {
n * 2; // computed but not returned
})
.then((v) => console.log(v)); // undefinedAn arrow function with a block body needs an explicit return. Without one, the next step receives undefined.
Expecting then to give back the value synchronously
const user = loadUser(1).then((u) => u); assigns a promise to user, not the user object. The value only exists inside a handler, or after await, which a later chapter covers.
Leaving a rejection with no handler
If nothing handles a rejected promise, the runtime reports an unhandled rejection. Node.js terminates the process by default. Ending a chain with catch prevents this. A later chapter covers the full rules.
Exercise
What does this code print, and in what order? const p = Promise.resolve(1); p.then((n) => console.log('a', n)); p.then((n) => n + 1).then((n) => console.log('b', n)); console.log('c');
Show answer
It prints "c", then "a 1", then "b 2". Handlers always run after the synchronous code, so "c" comes first. Both handlers registered directly on p receive 1 and run in registration order. The first logs "a 1". The second returns 2, and the chained handler logs "b 2" one step later.
Exercise
A colleague writes fetchData().then(render, showError). render sometimes throws a TypeError, and users see an unhandled rejection instead of the error message. Why, and how do you fix it?
Show answer
showError is a sibling of render, so it only handles rejections from fetchData(). It does not handle errors thrown inside render. The TypeError rejects the promise that then returns, and nothing handles that promise. Fix it with fetchData().then(render).catch(showError), so the catch sees rejections from both fetchData and render.
Exercise
What value or error reaches the final handlers in each chain? 1) Promise.resolve('x').finally(() => 'y').then(console.log) 2) Promise.reject(new Error('e1')).finally(() => { throw new Error('e2'); }).catch((e) => console.log(e.message))
Show answer
1) It logs "x". The return value of the finally handler is ignored, and the original value passes through. 2) It logs "e2". An error thrown inside finally replaces the original rejection, so e1 is lost.