Promises
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 15 of 24.
Callbacks inside callbacks get hard to follow, and each one must remember to check err.
node:fs/promises returns a promise instead: an object standing for a result that arrives later. .then(fn) runs with the result, .catch(fn) runs if any step before it failed, and .finally(fn) runs either way.
import { readFile } from 'node:fs/promises';
readFile('poem.txt', 'utf8')
.then((text) => console.log(text.length + ' characters'))
.catch(() => console.log('No poem today'))
.finally(() => console.log('Bye'));An error thrown inside .then lands in .catch too, so one handler covers the read and the parsing. A promise that fails with no .catch crashes the program.
Challenge
Easy- Rewrite
count.jswithreadFilefromnode:fs/promisesand.then. - A missing file now prints
No notes yet, from a.catch. Donestill comes last, from.finally.
Run node count.js, then node count.js nothere.json.
Try it yourself
import fs from 'node:fs';
const file = process.argv[2] ?? 'notes.json';
console.log('Reading...');
fs.readFile(file, 'utf8', (err, text) => {
if (err) {
console.log(`Cannot read ${file}`);
} else {
console.log(`${JSON.parse(text).length} notes`);
}
console.log('Done');
});
All lessons in Node.js Basics
1Running JavaScript on Node
Hello, NodeCommand-Line ArgumentsCommands