← Back to Node.js, page 3

nodejs-0051 · Easy fresher

How do util.promisify and util.callbackify work, and when does promisify give the wrong result?

util.promisify turns a function that takes an error-first callback as its last argument into a function that returns a promise. util.callbackify does the reverse. promisify gives a wrong result for functions whose callback does not follow the (err, value) rule, unless the function defines util.promisify.custom.

Full answer

Older Node APIs and many libraries use the callback style: the last argument is a function called with (err, result). Modern code prefers promises, because they work with async/await and try/catch.

util.promisify(fn) wraps such a function:

  • It calls fn with all the arguments you pass, plus its own callback as the last argument.
  • If the callback gets a truthy first argument, the promise rejects with it.
  • Otherwise the promise resolves with the second argument.

util.callbackify(asyncFn) does the opposite, which helps when old code must call new code. One detail: if the promise rejects with a falsy value (null, 0, ''), callbackify wraps it in an Error, because a falsy first argument would mean success.

When promisify goes wrong:

  • A callback that does not use (err, value). Example: a legacy function that calls cb(true) for "yes". promisify treats true as an error and rejects.
  • A callback with several result values, such as cb(null, a, b). Only the first result is kept.
  • Methods that use this. Pass a bound function: promisify(obj.method.bind(obj)).

The fix for odd callbacks is util.promisify.custom, a symbol property that holds the promise-returning version. Core functions use it: promisify(setTimeout) returns a function (delay, value) that resolves with value after the delay. Many core modules also ship promise APIs already (fs/promises, timers/promises, dns/promises, stream/promises), so check before wrapping.

javascript
const { promisify, callbackify } = require('node:util');

// A normal error-first callback function.
function getMarks(student, callback) {
  setTimeout(() => {
    if (student === 'unknown') return callback(new Error('no such student'));
    callback(null, { student, marks: 82 });
  }, 5);
}
const getMarksAsync = promisify(getMarks);

// A legacy function with a non-standard callback: cb(true) means "open".
function isOpen(callback) {
  setImmediate(() => callback(true));
}

// Give promisify the right translation.
function isOpenWithCustom(callback) {
  setImmediate(() => callback(true));
}
isOpenWithCustom[promisify.custom] = () => new Promise((resolve) => isOpenWithCustom(resolve));

async function main() {
  console.log('resolved:', await getMarksAsync('Asha'));
  await getMarksAsync('unknown').catch((err) => console.log('rejected:', err.message));

  // promisify(setTimeout) is built in through promisify.custom: (delay, value)
  console.log('setTimeout value:', await promisify(setTimeout)(5, 'done waiting'));

  // The wrong translation: true is treated as an error.
  await promisify(isOpen)().catch((value) => console.log('plain promisify rejected with:', value));
  console.log('with promisify.custom:', await promisify(isOpenWithCustom)());

  // callbackify: promise function -> callback function
  const double = async (n) => n * 2;
  await new Promise((resolve) => {
    callbackify(double)(21, (err, result) => {
      console.log('callbackify result:', err, result);
      resolve();
    });
  });
}

main();

The isOpen example is the trap: the callback sends true as the first argument, so plain promisify rejects instead of resolving. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): resolved: { student: 'Asha', marks: 82 } rejected: no such student setTimeout value: done waiting plain promisify rejected with: true with promisify.custom: true callbackify result: null 42

Key points

  • promisify expects (err, value) callbacks as the last argument.
  • callbackify goes from promise to callback.
  • Non-standard callbacks need util.promisify.custom.
  • Prefer built-in promise APIs when they exist.

Common mistakes

  • Promisifying a method and losing this.
  • Promisifying a function whose callback is not error-first.
  • Wrapping fs functions when fs/promises already exists.
  • Ignoring that only the first result value is kept.

Follow-ups

  • How would you promisify a function that returns two values?
  • What does util.promisify.custom do on setTimeout?
  • When would you use callbackify in new code?

Tips

  • Name the error-first rule before anything else.
  • Show the cb(true) trap. It proves you read the rules, not only the headline.
  • Mention that most core modules already have promise versions.