Sub topic 11
Turning Callback APIs into Promise APIs
Many APIs you will meet still report results through callbacks. Older Node.js modules, third-party libraries, and browser features such as FileReader or the onload event on images all work this way. To use them in a promise chain or with await, you need a small adapter that turns "call me back later" into "here is a promise."
This chapter assumes you already know how to create a promise with new Promise, how then and catch consume it, and how async/await works. It also assumes you can run code in Node.js, because most of the examples use Node's fs and util modules.
The Error-First Callback Convention
Node.js core APIs follow one convention. The last argument is a callback, and that callback receives an error as its first argument. If the operation succeeded, the error is null and the result comes second.
const fs = require('node:fs');
fs.readFile(__filename, 'utf8', (err, data) => {
if (err) {
console.error('failed:', err.message);
return;
}
console.log('read', data.length, 'characters');
});The convention matters because every callback has the same shape. Code that converts one such function can convert all of them. A promise has two outcomes, fulfilled and rejected, and an error-first callback also has two outcomes, so each one maps onto the other:
| Callback receives | Promise outcome |
|---|---|
| `err` is truthy | `reject(err)` |
| `err` is `null` or `undefined` | `resolve(result)` |
Wrapping by Hand
The manual version puts the original call inside a Promise executor and routes the callback's arguments to resolve or reject.
const fs = require('node:fs');
function readFileManual(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
}
readFileManual(__filename)
.then((text) => console.log(text.length))
.catch((err) => console.error(err.message));The wrapper returns the promise right away. The executor starts the read, and the promise stays pending until Node calls the callback. Callers can now chain on it, pass it to Promise.all, or await it.
Using util.promisify
Writing that wrapper for every function gets repetitive, so Node ships util.promisify. It takes a function that follows the error-first convention and returns a version that returns a promise.
const fs = require('node:fs');
const { promisify } = require('node:util');
const readFileP = promisify(fs.readFile);
async function main() {
const text = await readFileP(__filename, 'utf8');
console.log(text.length);
}
main().catch((err) => console.error(err));promisify appends its own callback to whatever arguments you pass. That only works if the original function expects the callback as its last argument and calls it as (err, value). When either condition fails, you need one of the techniques later in this chapter.
What promisify does internally
A simplified version shows that promisify does nothing more than the manual wrapper:
function myPromisify(fn) {
return function (...args) {
return new Promise((resolve, reject) => {
fn.call(this, ...args, (err, value) => {
if (err) reject(err);
else resolve(value);
});
});
};
}
const fs = require('node:fs');
const readFileP = myPromisify(fs.readFile);
readFileP(__filename, 'utf8').then((text) => console.log(text.length));The returned function is a regular function, not an arrow function, so it can forward this with fn.call(this, ...). That detail matters for the first gotcha below.
Edge Cases and Gotchas
Methods lose their `this`
If you promisify a method by reading it off its object, the method is detached from that object. When it later runs, this is wrong.
const { promisify } = require('node:util');
const counter = {
count: 0,
increment(step, callback) {
setTimeout(() => {
this.count += step;
callback(null, this.count);
}, 10);
},
};
// Wrong: `this` inside increment will not be counter
// const incrementP = promisify(counter.increment);
const incrementP = promisify(counter.increment).bind(counter);
incrementP(5).then((n) => console.log('count is', n)); // count is 5You can also bind before promisifying: promisify(counter.increment.bind(counter)). Both versions work. Pick one and use it everywhere in your codebase.
Callbacks with more than one result
A plain error-first callback passes one result after the error. Some APIs pass several, such as (err, body, status). Plain promisify keeps only the first one, because a promise fulfills with a single value. To keep all of them, wrap by hand and combine the results into an object:
function legacyFetch(id, callback) {
setTimeout(() => callback(null, { id, name: 'item' + id }, 200), 10);
}
function fetchP(id) {
return new Promise((resolve, reject) => {
legacyFetch(id, (err, body, status) => {
if (err) reject(err);
else resolve({ body, status });
});
});
}
fetchP(7).then(({ body, status }) => console.log(status, body.name)); // 200 item7Supplying a custom promisified version
A library author can tell promisify which promise version to use by attaching it under the util.promisify.custom symbol. When that property exists, promisify returns it instead of building a generic wrapper. Node does this for dns.lookup, so the promisified dns.lookup resolves to { address, family } and keeps both values.
const { promisify } = require('node:util');
function legacyFetch(id, callback) {
setTimeout(() => callback(null, { id }, 200), 10);
}
legacyFetch[promisify.custom] = (id) =>
new Promise((resolve, reject) => {
legacyFetch(id, (err, body, status) => {
if (err) reject(err);
else resolve({ body, status });
});
});
const fetchP = promisify(legacyFetch);
console.log(fetchP === legacyFetch[promisify.custom]); // true
fetchP(3).then((r) => console.log(r)); // { body: { id: 3 }, status: 200 }Exceptions thrown inside the callback
The Promise constructor catches anything thrown synchronously inside the executor and turns it into a rejection. Code inside the callback runs later, on a separate turn of the event loop, after the executor has returned. An exception thrown there is not caught by the promise. It becomes an uncaught exception, and Node will crash the process.
const fs = require('node:fs');
function readJson(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, text) => {
if (err) return reject(err);
try {
resolve(JSON.parse(text)); // JSON.parse can throw
} catch (parseErr) {
reject(parseErr);
}
});
});
}
readJson(__filename).catch((err) => console.log('rejected:', err.name)); // rejected: SyntaxErrorThe safer pattern is to keep the callback minimal: resolve with the raw data, then do the parsing in a then, where thrown errors become rejections automatically.
const { promisify } = require('node:util');
const fs = require('node:fs');
const readFileP = promisify(fs.readFile);
readFileP(__filename, 'utf8')
.then((text) => JSON.parse(text))
.catch((err) => console.log('rejected:', err.name)); // rejected: SyntaxErrorCallbacks that fire more than once
Some buggy libraries call their callback twice, for example once with data and again with an error. A settled promise never changes state, so the second resolve or reject call is silently ignored. This protects your chain, but it also hides the bug. If the duplicate call matters, log it inside the wrapper.
APIs that do not follow the error-first convention
setTimeout takes its callback first. Browser APIs often split success and failure into separate callbacks or events. promisify cannot handle these, so wrap them by hand and connect each path to the matching function:
// Browser: resolves when the image loads, rejects on failure
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error('Failed to load ' + src));
img.src = src;
});
}
loadImage('https://example.com/logo.png')
.then((img) => console.log(img.width, img.height))
.catch((err) => console.error(err.message));Notice that the error path creates a real Error object. Rejecting with an Error gives callers a stack trace and a message property, which a bare string or event object does not.
Waiting for a Single Event
For objects that emit events, Node provides events.once. It returns a promise that fulfills with an array of the event's arguments. If the emitter emits 'error' first, the promise rejects instead.
const { once, EventEmitter } = require('node:events');
async function main() {
const emitter = new EventEmitter();
setTimeout(() => emitter.emit('ready', 42, 'ok'), 10);
const [code, label] = await once(emitter, 'ready');
console.log(code, label); // 42 ok
}
main();Prefer Built-in Promise APIs When They Exist
Before you write a wrapper, check whether a promise version already exists. Modern Node includes several:
| Callback API | Promise-based equivalent |
|---|---|
| `fs.readFile`, `fs.writeFile`, ... | `require('node:fs/promises')` |
| `setTimeout` | `require('node:timers/promises').setTimeout` |
| `stream.pipeline` | `require('node:stream/promises').pipeline` |
| `dns.lookup` | `require('node:dns/promises')` |
| One event from an emitter | `events.once` |
const fs = require('node:fs/promises');
const { setTimeout: sleep } = require('node:timers/promises');
async function main() {
await sleep(50);
const text = await fs.readFile(__filename, 'utf8');
console.log('read after delay:', text.length);
}
main().catch(console.error);The built-in versions are maintained alongside Node itself, handle edge cases the core team has already found, and save you from writing wrapper code that you then have to test.
Exercises
Exercise
You write const statP = promisify(fs.stat); and later call statP('missing.txt'). The file does not exist. What happens to the returned promise, and how do you handle it with async/await?
Show answer
fs.stat calls its callback with an ENOENT error as the first argument, so the promisified version rejects with that error. Inside an async function, put await statP('missing.txt') in a try block and handle the error in the catch block. You can check err.code === 'ENOENT' there to tell a missing file apart from other failures.
Exercise
Write a function wait(ms) that returns a promise fulfilling after ms milliseconds, without using util.promisify or timers/promises. Why can util.promisify not wrap setTimeout directly in the generic way?
Show answer
function wait(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } Generic promisify appends a callback as the last argument and expects it to be called with (err, value). setTimeout takes its callback as the first argument and never passes an error. (Node does attach a promisify.custom version to setTimeout, but that is a special case, not generic behavior.)
Exercise
A wrapper calls resolve(JSON.parse(text)) inside an fs.readFile callback with no try/catch. The file holds invalid JSON. Does the promise reject? Explain.
Show answer
No. The callback runs after the executor has already returned, so the Promise constructor's automatic catch does not apply. JSON.parse throws an uncaught exception, which crashes a Node process by default, and the promise stays pending forever. Fix it with try/catch inside the callback, or resolve with the raw text and parse it in a later then.