Implement promisify From Scratch in JavaScript
Implement promisify from scratch in JavaScript to turn error-first callbacks into promises, with this, multiple results and util.promisify.custom.

Node.js grew up on error-first callbacks: a function takes a callback as its last argument and calls it with (error, result). Promises and async functions are easier to compose, so a converter that turns one style into the other became a standard tool, and util.promisify is the built-in version. The interview question asks you to write it. The core is a closure around new Promise, and the details are in the questions after it: how this is kept for methods, what to do when the callback receives more than one result, how to deal with functions that already return a promise and how the built-in handles functions with a custom promise version, such as setTimeout. This post builds promisify on Node.js 24 step by step, with the output of each stage. The Promise internals it relies on are covered in implementing a Promise.
The callback convention
An error-first function takes its callback as the last parameter. It calls the callback exactly once, with null or undefined as the first argument and the result as the second when it works, and with an error as the first argument when it fails.
function readConfig(name, callback) {
setTimeout(() => {
if (name === "missing") {
callback(new Error(`no config named ${name}`));
return;
}
callback(null, { name, debug: true });
}, 5);
}
readConfig("app", (error, config) => console.log("callback:", error, config));
readConfig("missing", (error, config) => console.log("callback:", error.message, config));callback: null { name: 'app', debug: true }
callback: no config named missing undefinedThe success call passes null for the error, and the failure call passes only the error, so the result parameter is undefined. A promise version of this function is readConfig("app") returning a promise that fulfills with the config or rejects with the error.
The basic implementation
function promisify(fn) {
return function (...args) {
return new Promise((resolve, reject) => {
fn.call(this, ...args, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
};
}
const readConfigAsync = promisify(readConfig);
console.log(await readConfigAsync("app"));
try {
await readConfigAsync("missing");
} catch (error) {
console.log("rejected:", error.message);
}{ name: 'app', debug: true }
rejected: no config named missingThe returned function collects its arguments, appends a callback of its own, and calls the original. The callback settles the promise: any truthy first argument rejects, otherwise the second argument resolves. A promise settles once, so even a function that wrongly calls its callback twice cannot change the result after the first call.
The wrapper is a regular function and the call uses fn.call(this, ...), which keeps the receiver when a method is promisified and then called as a method. Without that, the method would lose its this.
const store = {
prefix: "item",
load(id, callback) {
setTimeout(() => callback(null, `${this.prefix}-${id}`), 1);
},
};
store.loadAsync = promisify(store.load);
console.log(await store.loadAsync(7));item-7Called as store.loadAsync(7), this is store, and the prefix is found. A promisified method that is detached from its object loses this, as any method does, and the failure depends on when the method uses this. When it is used synchronously, inside the executor, the exception becomes a rejection.
const strict = {
prefix: "item",
loadSync(id, callback) {
callback(null, `${this.prefix}-${id}`);
},
};
const lost = promisify(strict.loadSync);
try {
await lost(8);
} catch (error) {
console.log(error.name);
}TypeErrorThe synchronous throw inside the executor becomes a rejection, because the executor of new Promise catches exceptions. Without this, this.prefix fails with a TypeError.
Callbacks with several results
Some callbacks pass more than one value, such as fs.read with (error, bytesRead, buffer) or dns.lookup with (error, address, family). The basic version drops everything after the first. Two common designs are to resolve with an array of all the values, or to resolve with an object of named fields. The built-in util.promisify resolves with the first value, unless the function defines a custom version.
function lookup(host, callback) {
setTimeout(() => callback(null, "203.0.113.5", 4), 1);
}
function promisifyAll(fn) {
return function (...args) {
return new Promise((resolve, reject) => {
fn.call(this, ...args, (error, ...results) => {
if (error) {
reject(error);
} else {
resolve(results.length > 1 ? results : results[0]);
}
});
});
};
}
const [address, family] = await promisifyAll(lookup)("example.test");
console.log(address, family);
console.log(await promisify(lookup)("example.test"));203.0.113.5 4
203.0.113.5The array form keeps the extra values for callers that want them. It changes the type of the result depending on the number of values, which is a trap, and a mapping function that names the fields is cleaner for your own functions.
function promisifyNamed(fn, names) {
return function (...args) {
return new Promise((resolve, reject) => {
fn.call(this, ...args, (error, ...results) => {
if (error) {
reject(error);
return;
}
resolve(Object.fromEntries(names.map((name, index) => [name, results[index]])));
});
});
};
}
console.log(await promisifyNamed(lookup, ["address", "family"])("example.test"));{ address: '203.0.113.5', family: 4 }The truthy check on the error
The test if (error) treats any truthy first argument as a failure. Some old APIs pass false, 0, "" or null for "no error", and all of them are falsy, so they work. A few APIs pass a non-error truthy value as a success flag as the first argument, such as fs.exists, whose callback receives only one boolean and no error. Those functions do not follow the convention, and promisify cannot guess. Node.js handles fs.exists with a custom version, and you would do the same with a wrapper.
function exists(path, callback) {
setTimeout(() => callback(path === "/etc"), 1);
}
console.log(await new Promise((resolve) => exists("/etc", resolve)));
try {
await promisify(exists)("/etc");
} catch (error) {
console.log("rejected with:", error);
}true
rejected with: trueThe boolean true was taken as an error, so the promise rejected with true. A function whose callback has no error argument needs its own adapter, as the new Promise wrapper above shows.
Functions that already return a promise, and custom versions
If fn already returns a promise and takes no callback, wrapping it would add a callback argument that is never called, and the promise would never settle. The built-in does not detect this, and neither should you: the caller decides what to promisify. But the built-in supports a special symbol, util.promisify.custom, that lets a function provide its own promise version. That is how setTimeout works.
import { promisify as nodePromisify } from "node:util";
import { setTimeout as sleepFromTimers } from "node:timers/promises";
console.log(nodePromisify.custom === Symbol.for("nodejs.util.promisify.custom"));
const delay = nodePromisify(setTimeout);
console.log(await delay(5, "value after 5 ms"));
console.log(delay === sleepFromTimers);true
value after 5 ms
truesetTimeout normally takes (callback, ms), with the callback first, which does not fit the convention. It defines util.promisify.custom, so promisify(setTimeout) returns a function that takes (ms, value) and resolves with the value, and that function is the same as setTimeout from node:timers/promises. You can support the same hook.
function promisifyCustom(fn) {
const custom = fn[Symbol.for("nodejs.util.promisify.custom")];
if (typeof custom === "function") {
return custom;
}
return promisify(fn);
}
function legacy(callback) {
callback(null, "legacy result");
}
legacy[Symbol.for("nodejs.util.promisify.custom")] = () => Promise.resolve("custom result");
console.log(await promisifyCustom(legacy)());
console.log(await promisifyCustom((callback) => callback(null, "plain"))());custom result
plainModern alternatives
Many Node.js APIs now ship a promise version, so promisifying is less needed than it was. Use node:fs/promises for files, node:timers/promises for timers, node:dns/promises for lookups and fetch for HTTP. util.promisify is still the right tool for third party callback libraries and old code. And for the reverse, util.callbackify turns a promise function back into a callback one.
import { callbackify } from "node:util";
const double = async (n) => n * 2;
callbackify(double)(21, (error, result) => console.log(error, result));null 42Pitfalls that cause hanging promises
The most common failure with a promisified function is a promise that never settles. It has three usual causes. The original function takes its callback in a position other than the last, as setTimeout does, so the appended callback lands in a parameter that the function ignores. The function calls its callback only on success and returns silently on failure. Or the function is an event emitter style API that reports through events and not through a callback, so there is nothing to wait for. In all three cases the wrapper cannot tell, so the symptom is only that await never returns.
A second family of problems is double calls. A badly written callback API can call its callback twice, once with an error and once with a result. A promise settles once, so the first call wins and the second is ignored, which hides the bug. If you suspect it, log inside the wrapper callback while you debug.
Finally, remember that wrapping adds one microtask of delay compared with calling the callback directly, and that errors thrown inside the callback of a native API are not turned into rejections. Only the synchronous call and the error argument are covered. For anything else, prefer the promise version of the API that Node.js provides.
Tests
import test from "node:test";
import assert from "node:assert/strict";
test("promisify resolves with the callback result", async () => {
const add = (a, b, cb) => cb(null, a + b);
assert.equal(await promisify(add)(1, 2), 3);
});
test("promisify rejects with the callback error", async () => {
const bad = (cb) => cb(new Error("nope"));
await assert.rejects(promisify(bad)(), /nope/);
});ℹ tests 2
ℹ pass 2
ℹ fail 0How to present it
State the convention first: the callback is last, and it receives the error first. Write the new Promise wrapper in a few lines and run it on a toy function. Then add this forwarding, and say why an arrow function as the wrapper would be wrong. The questions about multiple results and util.promisify.custom are the extensions that show depth. If asked about errors, describe the two sources: the callback's first argument, and a synchronous throw from fn, which the executor turns into a rejection.


