Sub topic 12
From Callbacks to Promises and async/await
This chapter assumes you know error-first callbacks, the microtask queue, and the reliability problems described in the inversion-of-control chapter. It also assumes you have seen Promise, .then(), and async/await before, even if you have not used them much.
Promises did not replace callbacks. They wrap them. A Promise is an object that stands for a value that will be ready later. It accepts callbacks through .then() and .catch(), and it applies fixed rules to them: each callback runs at most once, always asynchronously, and errors move along one standard path. async/await is syntax built on top of Promises.
Why Promises Fix Callback Problems
The earlier chapters listed what can go wrong when you hand a callback to someone else's code. The table shows how a Promise handles each of those problems.
| Callback problem | What a Promise guarantees |
|---|---|
| Callback invoked twice | A Promise settles once. Later `resolve` or `reject` calls are ignored. |
| Sometimes sync, sometimes async | `.then()` handlers always run as microtasks, after the current code finishes. |
| Error forgotten or thrown away | A rejection flows to the next `.catch()`, or to `try`/`catch` with `await`. |
| Deep nesting | Chained `.then()` calls or sequential `await` lines stay flat. |
Wrapping a Callback API by Hand
The Promise constructor takes an executor function. JavaScript calls the executor right away and passes it resolve and reject. You call the callback-based API inside the executor and connect its result to those two functions.
The simplest case has no error path:
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
delay(500).then(() => console.log('half a second later'));For an error-first API, send err to reject and the result to resolve:
const fs = require('node:fs');
function readFileAsync(path, encoding) {
return new Promise((resolve, reject) => {
fs.readFile(path, encoding, (err, data) => {
if (err) {
reject(err);
return;
}
resolve(data);
});
});
}
readFileAsync('config.json', 'utf8')
.then((text) => console.log('Read', text.length, 'characters'))
.catch((err) => console.error('Read failed:', err.message));The return after reject is not strictly needed, because a settled Promise ignores later calls. It still makes the intent clear and keeps any code below it from running.
util.promisify
Node.js includes this wrapper as util.promisify. It works on any function whose last parameter is an error-first callback that is called once:
const util = require('node:util');
const fs = require('node:fs');
const readFile = util.promisify(fs.readFile);
async function main() {
const text = await readFile('config.json', 'utf8');
console.log('Read', text.length, 'characters');
}
main().catch((err) => console.error(err.message));Most Node.js core modules also ship Promise versions directly, such as require('node:fs/promises'). Prefer those when they exist.
How await Resumes
When an async function reaches await, it pauses and returns control to the event loop. When the awaited Promise settles, the rest of the function is queued as a microtask.
What Not to Promisify
Promises fit operations that finish once. Event listeners, which can fire many times, do not fit that model. Converting emitter.on('data', ...) into a single Promise would capture only the first event. Keep listeners as callbacks. For a one-time event, Node.js offers events.once(emitter, 'name'), which returns a Promise.
Synchronous callbacks such as those passed to map or filter stay as they are. Wrapping them adds a delay and gives you nothing in return.
Exercise
Write a function waitForTimeoutOrError(ms, shouldFail) that returns a Promise. After ms milliseconds it rejects with new Error('failed') if shouldFail is true, and otherwise resolves with the string 'done'. Then explain what happens if your executor accidentally calls both resolve and reject.
Show answer
function waitForTimeoutOrError(ms, shouldFail) { return new Promise((resolve, reject) => { setTimeout(() => { if (shouldFail) { reject(new Error('failed')); return; } resolve('done'); }, ms); }); } If both are called, only the first call counts. The Promise settles once, and any later resolve or reject call is ignored.
Exercise
Why does util.promisify(db.query) fail when query reads this.connection internally, and how do you fix it?
Show answer
util.promisify stores a bare function reference and calls it without db as its receiver, so this is undefined inside query. Bind it first: util.promisify(db.query.bind(db)).