util.promisify Wraps Error First Callbacks

Wrap error-first Node.js callbacks with util.promisify to turn them into promise-returning functions, including custom callbacks shaped as (err, result).

JavascriptCli Tooling

Code

javascriptsnippet
18 lines
import { promisify } from 'node:util';

// 错误优先回调(error-first,签名为 (err, result))可整体包装成 Promise 风格
const sleep = promisify(setTimeout);

async function main() {
  const started = Date.now();
  await sleep(30);
  console.log('slept about', Date.now() - started, 'ms');

  // 自定义错误优先回调同样适用
  const readLogSize = promisify((name, cb) => {
    setTimeout(() => cb(null, name + ': 42 bytes'), 10);
  });
  console.log(await readLogSize('metrics.log'));
}

main();

Output

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

slept about 42 ms
metrics.log: 42 bytes

How it works

Count the function main as the entire surface area of util.promisify Wraps Error First Callbacks.

Await points sequence the asynchronous work; a rejection lands at the awaiting line. The import names the platform contact area: promisify, all from node:util.

What to watch for

  • node:util is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Applying it

The primary signature is async function main()

Running the file prints labeled results such as slept about — each operation’s effect is visible in the output.

Statements that matter

setTimeout(() => cb(null, name + ': 42 bytes'), 10);
await sleep(30);

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Nothing needs installing: `node:util` ships with Node.js itself.