← Back to Node.js, page 10

nodejs-0191 · Easy fresher

Implement promisify from scratch: how does it turn a Node-style callback function into a function that returns a promise?

promisify wraps a function whose last argument is an error-first callback (err, value). The wrapper returns a promise, calls the original with the same arguments plus its own callback, rejects when err is set, and resolves with the value otherwise. Keep this, catch synchronous throws (the Promise constructor does this for you), and honour util.promisify.custom for functions that already have a promise version.

Full answer

The contract of a Node-style function: the last argument is a callback, called once as callback(err, result). Success passes null or undefined as err.

Steps

  1. Return a new function that keeps this (use a normal function, not an arrow function) and collects the arguments.
  2. Return new Promise((resolve, reject) => ...). Inside, call the original function with the arguments plus a callback.
  3. In the callback: if err is truthy, reject(err). Otherwise resolve(value).
  4. Some callbacks pass more than one result, for example (err, a, b). util.promisify resolves with only the first value unless the function defines util.promisify.custom. A simple version can resolve with an array when there is more than one value.
  5. If the original throws synchronously, the Promise executor turns it into a rejection, so the caller never sees a sync exception.
  6. Respect util.promisify.custom: if the function has that symbol property, return it, so that functions like setTimeout (which has a custom version) and fs.exists work as expected.

Limits: the callback must be called exactly once. Functions that call the callback twice, or that are event based (streams), are not suitable. Prefer the built-in util.promisify and the fs/promises family in real code.

javascript
const util = require('node:util');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

function promisify(fn) {
  if (typeof fn !== 'function') throw new TypeError('fn must be a function');
  if (typeof fn[util.promisify.custom] === 'function') return fn[util.promisify.custom];
  return function (...args) {
    return new Promise((resolve, reject) => {
      fn.call(this, ...args, (err, ...values) => {
        if (err) reject(err);
        else resolve(values.length > 1 ? values : values[0]);
      });
    });
  };
}

(async () => {
  const file = path.join(os.tmpdir(), 'promisify-demo.txt');
  fs.writeFileSync(file, 'hello');

  console.log('1.', await promisify(fs.readFile)(file, 'utf8'));
  console.log('2.', await promisify(fs.readFile)(file + '.missing').catch((e) => e.code));

  const calculator = { base: 10, add(x, cb) { setImmediate(() => cb(null, this.base + x)); } };
  calculator.addAsync = promisify(calculator.add);
  console.log('3. this is kept:', await calculator.addAsync(5));

  const pair = (cb) => cb(null, 'a', 'b');
  console.log('4. two values:', await promisify(pair)());

  const throwsNow = () => { throw new Error('sync failure'); };
  console.log('5.', await promisify(throwsNow)().catch((e) => e.message));

  console.log('6. custom version used:', promisify(setTimeout) === setTimeout[util.promisify.custom]);
  fs.unlinkSync(file);
})();

Each numbered line checks one rule of the contract on the real fs module and small test functions. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. hello 2. ENOENT 3. this is kept: 15 4. two values: [ 'a', 'b' ] 5. sync failure 6. custom version used: true

Key points

  • Return a promise and call the original with an added callback.
  • Reject on err, resolve on the value.
  • Keep this by using a normal function.
  • The Promise executor turns a sync throw into a rejection.
  • Use util.promisify in real code.

Common mistakes

  • Using an arrow function and losing this.
  • Forgetting that the callback can receive several values.
  • Promisifying a function that calls its callback more than once.
  • Not rejecting when err is a falsy but meaningful value such as 0 (rare, but check for null or undefined).
  • Writing your own version when fs/promises already exists.

Follow-ups

  • How would you write the reverse, callbackify?
  • What does util.promisify.custom do?
  • Why is the Promise constructor safe against synchronous throws?

Tips

  • State the callback contract first.
  • Mention this and multiple values.
  • Say that you would use the built-in version.