callbackify Adapts Promises To Error-First Callbacks

Adapt promise-returning functions to the classic Node error-first callback shape with util.callbackify, rejections included.

JavascriptCli Tooling

Code

javascriptsnippet
25 lines
import { callbackify } from 'node:util';

// callbackify turns a promise-returning function into the classic
// Node error-first callback shape
const loadConfig = callbackify(async (name) => {
  return `${name}:ttl=60`;
});

loadConfig('cache', (err, value) => {
  if (err) {
    console.log('failed:', err.message);
    return;
  }
  console.log('loaded:', value);
});

// Rejections arrive as the first callback argument instead of
// surfacing as unhandled promise rejections
const flaky = callbackify(async () => {
  throw new Error('config store down');
});

flaky((err) => {
  console.log('failed:', err.message);
});

Output

Captured from a sandboxed run of this snippet in the build pipeline.

loaded: cache:ttl=60
failed: config store down

What callbackify hands to the callback

callbackify(async (name) => { return ${name}:ttl=60 }) returns loadConfig, a function in the classic Node error-first callback shape. The resolved value arrives as the second argument, so the first call logs loaded: cache:ttl=60. When the wrapped function rejects — flaky throws new Error('config store down') — the rejection is delivered as the first err argument instead of surfacing as an unhandled promise rejection, and the second call logs failed: config store down.

Order and branching in the demo

loaded: cache:ttl=60
failed: config store down

Inside loadConfig’s callback the if (err) guard is the branching point: on success it is skipped and console.log('loaded:', value) runs. flaky’s callback has no success path at all — it only ever reads err.message.

The line that converts a rejection

const flaky = callbackify(async () => {
  throw new Error('config store down');
});

The thrown Error never escapes as an uncaught exception: util.callbackify converts it into the callback’s first argument, which is the entire point of the adapter.

Interactive Tools for This Topic

FAQ

Is there any input checking?
No input check exists: the `Error` fires whenever execution reaches its line, not in response to any data shape.
Do I need to install anything before running this?
Nothing needs installing: `node:util` ships with Node.js itself.