At the end of Watch a Promise Settle, picksPromise went from pending to fulfilled and kept the text of picks.txt. But the timer only let you peek at it. On a slower disk, the same peek could still have shown <pending>. The Adeyemi family’s planning script needs a sturdier way to run its next step whenever the picks arrive, however long that takes.
In this lesson, you’ll give a promise the code to run when it’s fulfilled, when it’s rejected, and when it settles either way. By the end, your script will log the first line of the family’s picks, explain clearly when the file is missing, and say when it’s done in both cases. Start with the outcome you’re hoping for, where the file loads.
Run Code When a Promise Is Fulfilled
Your script can’t know when the read will finish, so it hands the promise a function to call when it does. You briefly met .then() in From Callbacks to Promises. The function you pass it is a handler. Once the promise is fulfilled, your handler runs with its value, after the code that’s running now has finished. Every promise has .then(), because Promise is part of JavaScript itself, not something Node adds.
Keep working in your museum folder, where picks.txt still holds the family’s picks introduced in From Callbacks to Promises:
picks.txt
Tolu: 28560, 111628
Grandma Bisi: 27992
Folake: 6565, 20684
Tunde: 16568
Next to it, save this script as first_pick.mjs. Its handler takes the text, extracts the first line, and logs it:
first_pick.mjs
import { readFile } from "node:fs/promises";
const picksPromise = readFile("picks.txt", "utf8");
picksPromise.then((picks) => {
const firstLine = picks.split("\n")[0];
console.log(`First line: ${firstLine}`);
});
console.log("Waiting for the picks...");
Run it, and the line at the bottom of the script prints first:
$ node first_pick.mjs
Waiting for the picks...
First line: Tolu: 28560, 111628
The script runs from top to bottom without stopping. The readFile() call returns a pending promise, and .then() attaches the handler and returns straight away. Then the last line logs Waiting for the picks.... Later, Node finishes reading, the promise is fulfilled, and your handler runs with the file’s text as picks.
That’s why every line that needs the picks goes inside the handler. Outside it, your script only has the promise. Inside it, picks is the text.
So far, the handler was waiting before the promise settled. In Watch a Promise Settle, though, the promise kept its value long after it settled. Does a handler that you attach after that moment still get the value?
To find out, you need a promise that’s fulfilled at a known time, and Node has one ready. The module node:timers/promises has its own setTimeout(), which takes a delay and a value but no callback. It returns a promise that’s fulfilled with that value once the delay is over.
Its name clashes with the setTimeout() you already know, which takes a callback, so the import below renames the new one to delay with as. Picture Tolu waiting at the museum’s kiosk while it starts up, about 50 milliseconds in this toy version, and Grandma Bisi arriving at 200 milliseconds, after it’s ready:
kiosk_ready.mjs
import { setTimeout as delay } from "node:timers/promises";
const kioskReady = delay(50, "Kiosk ready");
kioskReady.then((message) => {
console.log(`Tolu sees: ${message}`);
});
setTimeout(() => {
kioskReady.then((message) => {
console.log(`Bisi sees: ${message}`);
});
}, 200);
Tolu’s handler is attached straight away, while kioskReady is pending. Bisi’s is attached inside the callback of the familiar setTimeout(), roughly 150 milliseconds after the promise was fulfilled. Before you run node kiosk_ready.mjs, decide whether Bisi sees anything, and what.
Both of them see the same message:
$ node kiosk_ready.mjs
Tolu sees: Kiosk ready
Bisi sees: Kiosk ready
Tolu’s handler runs once the promise is fulfilled, at about 50 milliseconds. Bisi’s handler is attached at about 200 milliseconds to a promise that’s already fulfilled, and it still runs, with the same value.
A timer’s callback or an event works differently. It happens once, and code that wasn’t listening at that moment misses it. A settled promise keeps its value and hands it to every handler, whenever you attach it. And because a promise settles only once, that value won’t change.
If the late handler surprised you, then try putting the rule in your own words. This button opens a chat with your AI mentor, with the question below already typed and a pointer to this section. Add your explanation before you send it:
Catch a Rejection With .catch()
A handler for success covers only half of what can happen, because reads fail. In the last question of From Callbacks to Promises, Folake pointed the script at old_picks.txt, which doesn’t exist. The promise was rejected, the .then() handler never ran, and Node stopped the script with an ENOENT error, because nothing handled the rejection.
The .catch() method takes a handler for a rejection. That handler gets the reason the promise was rejected, which for a failed read is an Error object. Write .catch() right after .then(), as one chain: each line that starts with a dot calls a method on the result of the line above it.
Change first_pick.mjs to read Folake’s missing file, and give the chain a .catch() at the end:
first_pick.mjs
import { readFile } from "node:fs/promises";
readFile("old_picks.txt", "utf8")
.then((picks) => {
const firstLine = picks.split("\n")[0];
console.log(`First line: ${firstLine}`);
})
.catch((error) => {
console.log(`Couldn't read the picks: ${error.message}`);
});
console.log("Waiting for the picks...");
You no longer store the promise from readFile() in a variable: you call .then() on it directly. Run the script, and it explains the problem instead of crashing:
$ node first_pick.mjs
Waiting for the picks...
Couldn't read the picks: ENOENT: no such file or directory, open 'old_picks.txt'
The promise was rejected, so the .then() handler was skipped, and the .catch() handler logged the error’s message. The script then ended normally, without Node’s error. Strictly, .catch() is attached to a new promise that .then() hands back, which is rejected with the same error. How that works comes in a later lesson. That’s all you need to know about chains for now.
Editing the path to test a failure gets tedious. JavaScript has two shortcuts that make a promise that’s already settled. Given a plain value like a string, Promise.resolve(value) gives back a promise fulfilled with it, and Promise.reject(reason) gives back one rejected with reason. Pass Promise.resolve() a promise, though, and you get one that follows that promise’s outcome, pending or not. These shortcuts let you try handlers without a file:
try_handlers.mjs
const found = Promise.resolve("Tolu: 28560, 111628");
const missing = Promise.reject(new Error("Kiosk offline"));
found
.then((line) => console.log(`Fulfilled: ${line}`))
.catch((error) => console.log(`Rejected: ${error.message}`));
missing
.then((line) => console.log(`Fulfilled: ${line}`))
.catch((error) => console.log(`Rejected: ${error.message}`));
Both chains are the same, and only the promise at the start differs:
$ node try_handlers.mjs
Fulfilled: Tolu: 28560, 111628
Rejected: Kiosk offline
Each promise ran exactly one of the two handlers: the fulfilled one its .then() handler, and the rejected one its .catch() handler.
Finish Either Way With .finally()
Some work belongs after the read, regardless of its outcome, such as a line saying the check is done. You could write it in both handlers, but then you’d have to keep two copies in sync.
The .finally() method takes a handler that runs once the promise settles, fulfilled or rejected. It gets no argument, because it’s there for work that doesn’t depend on the outcome.
If .catch() and .finally() remind you of the catch and finally blocks of a try...catch statement, then that’s the right picture for what each handler is for. The difference is that a promise’s handlers run later, when it settles.
Point first_pick.mjs back at picks.txt, and add .finally() to the end of the chain:
first_pick.mjs
import { readFile } from "node:fs/promises";
readFile("picks.txt", "utf8")
.then((picks) => {
const firstLine = picks.split("\n")[0];
console.log(`First line: ${firstLine}`);
})
.catch((error) => {
console.log(`Couldn't read the picks: ${error.message}`);
})
.finally(() => {
console.log("Done checking the picks");
});
console.log("Waiting for the picks...");
Run it again, and the last line comes from .finally():
$ node first_pick.mjs
Waiting for the picks...
First line: Tolu: 28560, 111628
Done checking the picks
The .then() handler ran, the .catch() handler was skipped, and the .finally() handler ran last. Point the script at old_picks.txt again, and the middle line becomes Couldn't read the picks: ENOENT: no such file or directory, open 'old_picks.txt', while Done checking the picks still comes last.
Here, either the .then() handler or the .catch() handler runs, followed by the .finally() handler. One exception: if the .then() handler itself throws, the .catch() handler gets that error too, so both handlers can run.
Check Your Understanding
Tunde uses the shortcuts to test a chain for the museum’s galleries:
gallery_check.mjs
Promise.reject(new Error("Gallery 240 is closed"))
.then(() => console.log("Gallery open"))
.catch((error) => console.log(error.message))
.finally(() => console.log("Checked the gallery"));
console.log("Checking...");
When Tunde runs it, the script prints this:
$ node gallery_check.mjs
Checking...
Gallery 240 is closed
Checked the gallery
Try these questions before you open the answers:
- Explain this output. Which state is the promise from
Promise.reject()in, which handlers run, and why doesChecking...come first? - Folake reads
picks.txtwithout using.finally(). She writesconsole.log("Done checking the picks");as the last line offirst_pick.mjs, after the chain. Why does it print before the first line of the picks?
Checking...comes first, because the script runs to its end before any handler runs. The promise is rejected from the start, so the.then()handler is skipped, the.catch()handler logs the error’s message, and the.finally()handler runs last.- The last line runs straight away, while the promise from
readFile()is still pending. Only the handlers wait for the read. Anything that has to come after the picks belongs in a handler, and.finally()takes a handler for work that runs either way.
Identifying which handlers run gets quicker with practice. This button opens the mentor with a request ready to send. The mentor asks you a few short questions about promises and their handlers, one at a time:
Your planning script now reads the picks, handles a missing file, and finishes cleanly either way. Next, in Exercise: Read the Family’s Picks, you’ll write your own code to read the family’s picks and report them.
It’s the course’s first coding exercise, and it runs in your browser instead of your terminal. You edit the file in the editor and click Run Tests, and automated tests check your code. When a test fails, its message says what it expected and what it found, which tells you what to change next. Run the tests early and often, and click Full screen when you want more room. The Contents tab below the editor explains the rest.