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).
Code
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 bytesHow 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:utilis 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Do I need to install anything before running this?
- Nothing needs installing: `node:util` ships with Node.js itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.