In this lesson, you logged the Adeyemi family’s picksPromise twice, once straight away and once from a timer, and watched it go from pending to fulfilled.
Key Points
readFile()fromnode:fs/promisesgives back a promise straight away. It’s a placeholder for the text ofpicks.txt, not the text itself, so logging it right away showsPromise { <pending> }. Passing a callback to.then()hands you the text, but it doesn’t show you the promise itself.- To look at the same promise later, a
setTimeout()callback can log it again. The script runs on the call stack to its end, while Node reads the file and the timer waits, outside your code, in the waiting area. When the timer is due, its callback joins the task queue, and the event loop moves it onto the stack once the stack is empty. - In this run, Node finished reading long before the 100-millisecond timer was due. It took a short turn on the empty stack, put the text into the promise, and changed its state from pending to fulfilled. Node makes that change itself, once the read finishes. How Node hands the text over comes later in the course.
- A promise keeps its value, however late you look. Node shows a fulfilled promise’s text as a string, in quotes, with
\nfor each line break. - If the script asked for a file that isn’t there, like Folake’s
old_picks.txt, the read would fail, and the promise would be rejected instead, holding the reason, an error saying there’s no such file. - Fulfilled or rejected, the promise is settled, and it settles only once. It never goes back to pending, and it never switches between fulfilled and rejected.
The rule: a promise starts pending. It settles at most once, as fulfilled or rejected, and then it keeps its value.
The Final Code
The family’s picks, as you saved them in the last lesson:
picks.txt
Tolu: 28560, 111628
Grandma Bisi: 27992
Folake: 6565, 20684
Tunde: 16568
The script logs the promise straight away, then again from a timer 100 milliseconds later:
watch_picks.mjs
import { readFile } from "node:fs/promises";
const picksPromise = readFile("picks.txt", "utf8");
console.log(picksPromise);
setTimeout(() => {
console.log(picksPromise);
}, 100);
Run it with Node, and the same promise shows up twice, first pending, then holding the text. That’s this run’s output. On a slower disk, the read could still be pending when the timer looks.
$ node watch_picks.mjs
Promise { <pending> }
Promise {
'Tolu: 28560, 111628\nGrandma Bisi: 27992\nFolake: 6565, 20684\nTunde: 16568\n'
}
A timer only lets you peek. Real code can’t rely on how long a read takes. Next, in Handle Results With .then() and .catch(), you’ll take a proper look at .then(), and at .catch() for a rejection.