Sub topic 11
Turning Callback APIs into Promise APIs
This chapter assumes you know how to create a promise with new Promise, how then and catch consume one, and how async/await works. You also need Node.js to run the examples, since they use its fs and util modules.
Many older APIs report their results through callbacks instead of returning promises. Node.js core modules, older npm packages and browser APIs such as setTimeout all work this way. You can still use them in promise chains and async functions if you wrap each one in a function that returns a promise. This is called promisifying.
The error-first callback convention
Most Node.js callback APIs follow one rule. The last argument is a callback, and that callback receives (err, result). If the operation fails, err is an error object. If it succeeds, err is null and result holds the value.
This rule lines up with a promise's two outcomes. A non-null err maps to reject, and a successful result maps to resolve.
Wrapping by hand
To wrap an API by hand, call it inside the Promise constructor and forward the callback's arguments to resolve or reject:
const fs = require('node:fs');
const { promisify } = require('node:util');
// Manual wrapping of a Node-style callback API
function readFileManual(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
}
// Built-in helper for the same pattern
const readFileP = promisify(fs.readFile);
readFileManual(__filename).then((text) => console.log(text.length));
readFileP(__filename, 'utf8').then((text) => console.log(text.length));Both versions print the same length. util.promisify takes any function that follows the error-first convention and returns a version that returns a promise. It passes your arguments through and adds the callback for you.
APIs that don't follow the convention
setTimeout takes the callback as its first argument, and that callback never receives an error. promisify can't handle this shape, so you write a small wrapper:
function delay(ms, value) {
return new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
}
delay(100, 'done').then((v) => console.log(v));Other callback shapes need the same treatment. Event emitters and callbacks that receive several result values fall into this group. With multiple values, decide what the promise fulfills with. Usually that is an object or an array, because resolve uses only its first argument.
Common errors
The table lists the mistakes people make most often when promisifying.
| Mistake | Symptom | Fix |
|---|---|---|
| Promisifying a method without its object | `TypeError` because `this` is `undefined` | `promisify(obj.method).bind(obj)` or `promisify(obj.method.bind(obj))` |
| Missing `else` (or `return`) after `reject(err)` | `resolve` runs as well. It has no effect, but any code after it still runs | Use `if/else` or `return reject(err)` |
| Throwing inside the inner callback | The process crashes because the promise never sees the throw | Call `reject` instead of throwing in the callback |
| Wrapping APIs that already return promises | Redundant code | Use `fs.promises`, `timers/promises` and similar modules |
The third row needs a closer look. The Promise constructor only catches errors thrown synchronously inside the executor function. The fs.readFile callback runs later, on a different call stack. An error thrown there escapes the promise completely.
Using the wrapped function
After you wrap a function, it works with every promise tool:
const { readFile } = require('node:fs/promises');
async function sizes(paths) {
const texts = await Promise.all(paths.map((p) => readFile(p, 'utf8')));
return texts.map((t) => t.length);
}
sizes([__filename, __filename]).then(console.log).catch(console.error);Exercise
A legacy function getUser(id, callback) calls callback(err, user). Write getUserP(id) by hand so it returns a promise, and explain why throw err inside the callback would be wrong.
Show answer
function getUserP(id) { return new Promise((resolve, reject) => { getUser(id, (err, user) => { if (err) reject(err); else resolve(user); }); }); }. Throwing inside the callback is wrong because the callback runs after the executor has returned. The Promise constructor only catches synchronous throws from the executor, so the error would become an uncaught exception and the promise would stay pending forever.
Exercise
Why does const stat = promisify(client.stat) fail with a TypeError when called, while promisify(client.stat.bind(client)) works?
Show answer
Passing client.stat detaches the method from its object, so this is undefined when the promisified function calls it. Binding the method to client first keeps this pointing at the client.