← Back to JavaScript, page 6

javascript-0118 · Medium mid

How do you convert a callback-based function to a promise (promisify) and a promise-based function back to a callback (callbackify)?

Promisify returns a function that wraps the call in a new Promise and passes a Node-style callback (error first) that rejects on an error and resolves with the result. Callbackify does the reverse: it calls the promise function and passes the outcome to a final callback. Keep this binding, handle functions with several results, and make sure a callback is never called twice.

Full answer

Node.js APIs use the error-first callback convention: fn(...args, (err, result) => {}). Modern code prefers promises, so conversion is a common task, and a good first coding question about promises.

promisify(fn) returns a new function. When it is called, it returns new Promise((resolve, reject) => ...) and calls fn with the original arguments plus a callback. The callback rejects with err when it is truthy, otherwise resolves with result. Details that matter:

  • Preserve this: return a regular function and call fn.apply(this, args), so methods like obj.read still work.
  • Callbacks that give several results, such as (err, a, b), cannot be expressed by one resolved value. Resolve with an array or an object, or use a custom symbol as Node does with util.promisify.custom.
  • If fn throws synchronously, the Promise constructor catches it and rejects, which is what you want.
  • Some APIs call the callback more than once. A Promise settles only once, so later calls are ignored. That is fine for one-shot calls and wrong for events.

callbackify(fn) goes the other way. It returns a function that takes the original arguments and a final callback. It calls fn(...args), then calls callback(null, value) on success or callback(error) on failure. Call the callback outside the promise chain, for example in queueMicrotask or process.nextTick, so an exception thrown by the callback is not swallowed by the promise and turned into a second callback call.

In real Node.js code, use util.promisify and util.callbackify, or the built-in promise APIs such as fs/promises, and use these hand-made versions to explain how they work. For browser callback APIs that do not use error-first style, write a custom wrapper.

javascript
function promisify(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]);
      });
    });
  };
}

function callbackify(fn) {
  return function (...args) {
    const callback = args.pop();
    fn.apply(this, args).then(
      (value) => queueMicrotask(() => callback(null, value)),
      (error) => queueMicrotask(() => callback(error)),
    );
  };
}

// a callback style function that is async on purpose
function divide(a, b, callback) {
  setTimeout(() => {
    if (b === 0) callback(new Error('division by zero'));
    else callback(null, a / b);
  }, 5);
}

const counter = {
  base: 100,
  addAsync(n, callback) {
    setTimeout(() => callback(null, this.base + n, 'extra'), 1);
  },
};

async function main() {
  const divideAsync = promisify(divide);
  console.log(await divideAsync(10, 4));
  try {
    await divideAsync(1, 0);
  } catch (error) {
    console.log('rejected:', error.message);
  }

  counter.addPromise = promisify(counter.addAsync);
  console.log('keeps this and many results:', await counter.addPromise(5));

  const asyncSquare = async (n) => {
    if (n < 0) throw new RangeError('negative');
    return n * n;
  };
  const squareCb = callbackify(asyncSquare);
  await new Promise((done) => {
    squareCb(7, (error, value) => { console.log('callback result:', error, value); done(); });
  });
  await new Promise((done) => {
    squareCb(-1, (error, value) => { console.log('callback error:', error.name, value); done(); });
  });

  const { promisify: nodePromisify } = require('node:util');
  console.log('util.promisify gives the same answer:', await nodePromisify(divide)(9, 3));
}
main();

Run with Node.js v24.22.1 as js-118.js; two runs gave identical output. Output: 2.5 rejected: division by zero keeps this and many results: [ 105, 'extra' ] callback result: null 49 callback error: RangeError undefined util.promisify gives the same answer: 3

Key points

  • Promisify wraps the call in a new Promise and passes an error-first callback that rejects or resolves.
  • Preserve this with a regular function and apply; synchronous throws become rejections.
  • Several callback results need an array or object; a Promise settles only once.
  • Callbackify calls the callback outside the promise chain to avoid double calls.
  • Prefer util.promisify, util.callbackify, and fs/promises in real code.

Common mistakes

  • Forgetting to bind this and breaking methods.
  • Resolving with only the first value when the callback passes several results.
  • Calling the final callback inside the then handler, so an exception in the callback triggers a second call through the catch handler.
  • Promisifying APIs that call the callback many times, such as event listeners.

Follow-ups

  • What does util.promisify.custom do?
  • Why does fs/promises exist, and when would you still use callbacks?
  • How would you promisify an API where the callback is not the last argument?

Tips

  • Show the error-first convention and the Promise wrapper in a few lines.
  • Mention this binding and multiple results.
  • Say that real code should use util.promisify or fs/promises.