You already know what a promise is from the JavaScript course — an object representing a value that isn't ready yet. This lesson is about where promises show up specifically in Node, and how to get one when an API only offers callbacks.
The nested fs.readFile() calls from the last lesson use fs's callback API. Switching to fs/promises flattens it with .then() chains instead of nesting:
const fs = require('fs/promises')
fs.readFile('user.json', 'utf8')
.then((userData) => fs.readFile('settings.json', 'utf8'))
.then((settingsData) => fs.readFile('preferences.json', 'utf8'))
.then((prefData) => console.log('All data loaded'))
.catch((err) => console.error('Something failed:', err))One .catch() at the end now handles a failure from any step, instead of repeating the same error check in every callback.
Those three reads don't actually depend on each other — each one waits for the previous one to finish for no real reason. Promise.all() starts them all at once and waits for every one to finish:
Promise.all([
fs.readFile('user.json', 'utf8'),
fs.readFile('settings.json', 'utf8'),
fs.readFile('preferences.json', 'utf8'),
])
.then(([userData, settingsData, prefData]) => {
console.log('All data loaded')
})
.catch((err) => console.error('Something failed:', err))This finishes roughly as fast as the slowest single read, instead of the sum of all three — a real difference once a server is handling many requests.
Not every function offers a promise version. Node's built-in util.promisify() converts any error-first callback function into one that returns a promise:
const util = require('util')
const fs = require('fs')
const readFileAsync = util.promisify(fs.readFile)
readFileAsync('data.txt', 'utf8')
.then((data) => console.log(data))
.catch((err) => console.error(err))util.promisify() only works on functions that follow Node's error-first callback convention from the last lesson — the callback's first parameter must be the error. Most of Node's own APIs qualify.
| Situation | What typically rejects the promise |
|---|---|
| Reading a file | File doesn't exist, or the program lacks permission to read it |
| Making a network request | The other server is unreachable, or times out |
| Parsing JSON | The text isn't valid JSON |