Node.js theorytheory 0/50 · 0%
Patterns · medium

23. util.promisify and callback interop

Bridging older callback-based APIs into the Promise world.

Many older Node APIs (and some libraries) still use error-first callbacks. `util.promisify` wraps such a function into one that returns a Promise, so it can be used with `await`.

js
import { promisify } from "node:util";
import { exec } from "node:child_process";

const execAsync = promisify(exec);

const { stdout } = await execAsync("node --version");
console.log(stdout.trim());

`promisify` expects the wrapped function's last argument to be a standard `(err, result)` callback; functions that call back with multiple result values (or don't follow the convention) need a small manual wrapper instead.

Check your understanding

  1. 1. What calling convention does util.promisify expect from the wrapped function?

  2. 2. Why would you promisify an old callback-based API?

  3. 3. What must you do for a callback API that returns multiple values non-standardly?