util.promisify(original)


接受一个遵循常见错误优先回调风格的函数,即将 (err, value) => ... 回调作为最后一个参数,并返回一个返回 Promise 的版本。

【Takes a function following the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument, and returns a version that returns promises.】

import { promisify } from 'node:util';
import { stat } from 'node:fs';

const promisifiedStat = promisify(stat);
promisifiedStat('.').then((stats) => {
  // Do something with `stats`
}).catch((error) => {
  // Handle the error.
});const { promisify } = require('node:util');
const { stat } = require('node:fs');

const promisifiedStat = promisify(stat);
promisifiedStat('.').then((stats) => {
  // Do something with `stats`
}).catch((error) => {
  // Handle the error.
});

或者,等效地使用 async function

【Or, equivalently using async functions:】

import { promisify } from 'node:util';
import { stat } from 'node:fs';

const promisifiedStat = promisify(stat);

async function callStat() {
  const stats = await promisifiedStat('.');
  console.log(`This directory is owned by ${stats.uid}`);
}

callStat();const { promisify } = require('node:util');
const { stat } = require('node:fs');

const promisifiedStat = promisify(stat);

async function callStat() {
  const stats = await promisifiedStat('.');
  console.log(`This directory is owned by ${stats.uid}`);
}

callStat();

如果存在 original[util.promisify.custom] 属性,promisify 将返回它的值,见 自定义 promise 化函数

【If there is an original[util.promisify.custom] property present, promisify will return its value, see Custom promisified functions.】

promisify() 假设 original 在所有情况下都是以回调函数作为最后一个参数的函数。如果 original 不是函数,promisify() 将会抛出错误。如果 original 是函数,但它的最后一个参数不是以错误优先的回调函数,它仍然会被传入一个以错误为优先的回调函数作为最后一个参数。

在类方法或其他使用 this 的方法上使用 promisify() 可能无法按预期工作,除非进行特殊处理:

【Using promisify() on class methods or other methods that use this may not work as expected unless handled specially:】

import { promisify } from 'node:util';

class Foo {
  constructor() {
    this.a = 42;
  }

  bar(callback) {
    callback(null, this.a);
  }
}

const foo = new Foo();

const naiveBar = promisify(foo.bar);
// TypeError: Cannot read properties of undefined (reading 'a')
// naiveBar().then(a => console.log(a));

naiveBar.call(foo).then((a) => console.log(a)); // '42'

const bindBar = naiveBar.bind(foo);
bindBar().then((a) => console.log(a)); // '42'const { promisify } = require('node:util');

class Foo {
  constructor() {
    this.a = 42;
  }

  bar(callback) {
    callback(null, this.a);
  }
}

const foo = new Foo();

const naiveBar = promisify(foo.bar);
// TypeError: Cannot read properties of undefined (reading 'a')
// naiveBar().then(a => console.log(a));

naiveBar.call(foo).then((a) => console.log(a)); // '42'

const bindBar = naiveBar.bind(foo);
bindBar().then((a) => console.log(a)); // '42'