Time to start the Adeyemi family’s planning script. Almost every step of it waits for something, such as the file with Tolu’s, Grandma Bisi’s, Folake’s, and Tunde’s picks to load or the museum’s slow old kiosk to answer.
You already know one way to wait in JavaScript: hand a function a callback. In this lesson, you’ll see why callbacks get awkward as a script grows, meet the promise that replaces them, and learn what a promise is, and isn’t, when you log it.
Look Back at Nested Callbacks
Callbacks work, but each step that waits pushes the next one inside it. Here’s how the planning script would start with callbacks alone.
It reads picks.txt with readFile() from node:fs, then asks the kiosk about Tolu’s first pick with lookupArtwork(id, callback). That helper is a stand-in for the kiosk, and you’ll work with it later in the course. Both functions use error-first callbacks, so each callback’s first argument is an error or null when nothing went wrong:
readFile("picks.txt", "utf8", (err, picks) => {
if (err) {
console.log(`Couldn't read the picks: ${err.message}`);
return;
}
const id = firstPickOf(picks);
lookupArtwork(id, (err, artwork) => {
if (err) {
console.log(`Couldn't look up ${id}: ${err.message}`);
return;
}
// The gallery lookup would go one level deeper...
});
});
The firstPickOf() call stands for a line or two that pulls an ID out of the text, so you can skip over it and look at the shape of the code. The kiosk lookup can’t start until the picks have loaded, so it goes inside the first callback, with its own err check. A third step would go inside the second. Developers call this rightward drift, with its repeated checks and stacked closing brackets, callback hell.
The second problem is quieter. Once you hand your callback to lookupArtwork(), the helper decides when your callback runs, how often, and whether it runs at all. A buggy kiosk helper could call it twice, never, or before the call even returns. Giving that control away is called inversion of control.
What if readFile() didn’t take your callback at all, but handed something back straight away?
Get a Promise From readFile()
Node.js has a second version of readFile() that does exactly that. It lives in node:fs/promises, takes the same path and encoding but no callback. To try it, make a folder for the planning script and move into it:
$ mkdir museum
$ cd museum
In that folder, save the family’s picks with your editor. Each line holds a name and the IDs of that person’s artworks in the museum’s collection:
picks.txt
Tolu: 28560, 111628
Grandma Bisi: 27992
Folake: 6565, 20684
Tunde: 16568
Now save this script as read_picks.mjs. It reads the file, logs what readFile() gives back, and tries to log the file’s character count, as a quick check that the file loaded:
read_picks.mjs
import { readFile } from "node:fs/promises";
const picks = readFile("picks.txt", "utf8");
console.log(picks);
console.log(`Characters read: ${picks.length}`);
Before you run it, write down what you expect the two lines to show. Then run node read_picks.mjs and compare.
Neither line shows the picks:
$ node read_picks.mjs
Promise { <pending> }
Characters read: undefined
The name says picks, but the variable doesn’t hold the file’s text. It holds a Promise, an object that stands in for a value that isn’t ready yet. <pending> means Node.js is still reading the file. It’s the same now-and-later split you know from callbacks. readFile() starts the read, returns at once, and the script carries on. The text arrives later, when the script has already reached its last line.
The second line fails silently. A promise has no .length property, and reading a property an object doesn’t have gives undefined instead of throwing an error. So the script runs to the end without complaint.
If you haven’t run it yet, do that now, because the fix builds on what you see. Start by renaming the variable picksPromise, so its name says what it holds. The text comes out of the promise through .then(), a method you pass a callback to:
read_picks.mjs
import { readFile } from "node:fs/promises";
const picksPromise = readFile("picks.txt", "utf8");
console.log(picksPromise);
picksPromise.then((picks) => {
console.log(picks.trim());
console.log(`Characters read: ${picks.length}`);
});
Run it again, and the promise is still pending when the script logs it, but the text and its length follow:
$ node read_picks.mjs
Promise { <pending> }
Tolu: 28560, 111628
Grandma Bisi: 27992
Folake: 6565, 20684
Tunde: 16568
Characters read: 73
Your count may be a few characters off. The 73 assumes each line, the last one included, ends in a plain newline (LF). An editor that saves Windows-style line endings (CRLF) or leaves out the final newline gives a different number, and that’s fine.
JavaScript calls the function you passed to .then() once the text is ready, with the text as its argument. That’s still a callback, but you hand it to the promise, not to readFile(), and a promise follows fixed rules about calling it. A later lesson covers .then() in detail. That’s all you need about it for now.
If the difference between the promise and its text hasn’t clicked yet, try putting it 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:
Read a Promise’s State
The promise in picksPromise has a lifecycle, and <pending> is only its first stage. A promise is always in one of three states:
- Pending: The work is still going on, and there’s no value yet.
- Fulfilled: The work succeeded, and the promise holds its value. For
picksPromise, that’s the text ofpicks.txt. - Rejected: The work failed, and the promise holds the reason, usually an error. If
picks.txtwere missing, the promise would be rejected with anENOENTerror, the same kind the callback version passed you aserr.
A promise that’s fulfilled or rejected is settled, and it settles only once. After that, its state and its value never change. That fixed rule answers part of the kiosk worry from the start of this lesson, because a fulfilled promise can’t call your .then() callback twice or switch to an error afterward.
An order number at the museum café works much the same way. You order a sandwich and get a number straight away. The number isn’t your sandwich, and you can’t eat it, any more than you can read characters from picksPromise.
While the kitchen is still making it, there’s no sandwich yet. The order is pending, like the promise before the file has loaded. When the kitchen finishes, the order is done, and staff call your number, the way a promise calls your .then() callback.
Either you get the sandwich, and the order is fulfilled, or you hear they’ve run out, and it’s rejected. The comparison stops at the paper. Your number never changes, but a promise records its own outcome, so if you log it later, it can show something other than <pending>.
Check Your Understanding
Grandma Bisi moves the logging around in her copy of the script, attaching .then() before the two log lines:
bisi_picks.mjs
import { readFile } from "node:fs/promises";
const picksPromise = readFile("picks.txt", "utf8");
picksPromise.then((picks) => {
console.log("Picks loaded");
});
console.log(picksPromise);
console.log("Planning the visit...");
When she runs it, the two lines at the end of her script still come before the callback’s line:
$ node bisi_picks.mjs
Promise { <pending> }
Planning the visit...
Picks loaded
Try explaining these results before you open the answers:
- Why does
Picks loadedcome last, even though Bisi attached.then()before the two log lines? What state is the promise in when it’s logged? - Tunde wants each person’s picks on a line of their own, so he writes
const picks = readFile("picks.txt", "utf8");and thenconst lines = picks.split("\n");. His script crashes withTypeError: picks.split is not a function. Why does this line crash when the.lengthline earlier only gaveundefined? - Folake points
read_picks.mjsatold_picks.txt, which doesn’t exist. Node.js prints an error starting withENOENT: no such file or directory, the text is never logged, and the script stops with exit code 1. Which states did that promise go through, and why did the.then()callback never run?
- The promise is pending when it’s logged. Attaching
.then()first doesn’t make the file load any sooner. The callback runs only once the promise is fulfilled, after the script’s last line. - Reading the missing
.lengthproperty quietly gaveundefined, but calling a missing method throws aTypeError. Both come from treating the promise as the text. - It started pending, like every promise from
readFile(), then became rejected, holding theENOENTerror. Once rejected, it stays rejected. The.then()callback runs only for a fulfilled promise, so it never ran. Nothing in the script handled the rejection, so Node.js printed that error and stopped the script. Handling a rejection comes in a later lesson.
Predicting the state of a promise gets quicker with practice. This button opens the mentor with a request ready to send. The mentor asks you a few short questions about promise states, one at a time:
Your script now logs Promise { <pending> }, and you know that’s a placeholder for the family’s picks, not the picks themselves. But what happens to the promise between that log line and the moment the text arrives? Next, in Watch a Promise Settle, you’ll log the same promise before and after it settles and see it change.