Sub topic 5
Reacting to Results with then, catch and finally
This chapter assumes you can write arrow functions and closures, that you know the three promise states (pending, fulfilled, rejected), and that you can create a promise with new Promise or Promise.resolve. Here you will learn how to run code once a promise settles.
The working model
A promise holds a future result, and you can't read that result directly. You register handlers, which are functions the promise calls once it settles. You register them with three methods:
| Method | Runs when | Handler receives |
|---|---|---|
| `then(onFulfilled)` | the promise fulfills | the fulfillment value |
| `then(onFulfilled, onRejected)` | it fulfills or it rejects | the value or the reason |
| `catch(onRejected)` | the promise rejects | the rejection reason |
| `finally(onFinally)` | it fulfills or it rejects | nothing |
Each method returns a new promise, so you can attach another call to its result. The next chapter covers how values move through those new promises. For now, look at what each handler sees.
then: handling success
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
delay(100, 42).then((value) => {
console.log('got', value); // got 42
});
console.log('registered'); // logs firstregistered logs first. Handlers never run synchronously, even if the promise has already settled. They always wait until the code that is running now has finished.
You can attach a handler after the promise has settled and it still runs. A promise remembers its result, unlike an event emitter.
const p = Promise.resolve('ready');
setTimeout(() => {
p.then((v) => console.log('late handler:', v)); // late handler: ready
}, 500);catch: handling failure
catch(fn) is shorthand for then(undefined, fn). It runs when the promise rejects. It also runs when a handler earlier in the same chain throws.
const fail = new Promise((_, reject) => {
setTimeout(() => reject(new Error('timeout')), 100);
});
fail
.then((v) => console.log('never runs', v))
.catch((err) => console.log('caught:', err.message)); // caught: timeoutThe rejection skips the then handler and reaches catch.
finally: cleanup either way
finally runs whether the promise fulfilled or rejected. Use it for cleanup, such as hiding a spinner or closing a connection. Its handler gets no argument, and the original result passes through it to the next step unchanged.
Promise.resolve('data')
.finally(() => console.log('cleanup')) // cleanup
.then((v) => console.log(v)); // dataCommon errors
Passing a call instead of a function. p.then(console.log('x')) runs console.log straight away and passes undefined to then. Write p.then(() => console.log('x')).
Expecting the second argument of then to catch errors from the first. In p.then(onOk, onErr), onErr handles only a rejection of p. An error thrown inside onOk gets past it:
Promise.resolve(1)
.then(
() => { throw new Error('in handler'); },
() => console.log('not called')
)
.catch((err) => console.log('outer catch:', err.message)); // outer catch: in handlerPut a separate .catch() at the end instead.
Reading a value from finally. finally((v) => ...) always receives undefined. Read values in then.
Forgetting catch. A rejected promise with no rejection handler triggers an unhandled-rejection warning. In Node.js it crashes the process by default. A later chapter covers this in detail.
Exercise
What does this code log, and in what order? Promise.reject(new Error('x')).finally(() => console.log('A')).then(() => console.log('B')).catch((e) => console.log('C', e.message)); console.log('D');
Show answer
D, then A, then C x. The synchronous log D runs first because handlers never run synchronously. finally runs on the rejection and passes it along unchanged, so the then handler is skipped and catch logs "C x".
Exercise
In p.then(handleData, handleError), handleData throws. Does handleError run? How would you make sure the error gets handled?
Show answer
No. handleError responds only to a rejection of p itself. Write p.then(handleData).catch(handleError) so that catch also receives errors thrown inside handleData.