自定义的 promise 化函数


使用 util.promisify.custom 符号可以覆盖 util.promisify() 的返回值:

const util = require('node:util');

function doSomething(foo, callback) {
  // ...
}

doSomething[util.promisify.custom] = (foo) => {
  return getPromiseSomehow();
};

const promisified = util.promisify(doSomething);
console.log(promisified === doSomething[util.promisify.custom]);
// 打印 'true'

这对于原始函数不遵循将错误优先的回调作为最后一个参数的标准格式的情况很有用。

例如,对于接受 (foo, onSuccessCallback, onErrorCallback) 的函数:

doSomething[util.promisify.custom] = (foo) => {
  return new Promise((resolve, reject) => {
    doSomething(foo, resolve, reject);
  });
};

如果 promisify.custom 已定义但不是函数,则 promisify() 将抛出错误。

Using the util.promisify.custom symbol one can override the return value of util.promisify():

const util = require('node:util');

function doSomething(foo, callback) {
  // ...
}

doSomething[util.promisify.custom] = (foo) => {
  return getPromiseSomehow();
};

const promisified = util.promisify(doSomething);
console.log(promisified === doSomething[util.promisify.custom]);
// prints 'true'

This can be useful for cases where the original function does not follow the standard format of taking an error-first callback as the last argument.

For example, with a function that takes in (foo, onSuccessCallback, onErrorCallback):

doSomething[util.promisify.custom] = (foo) => {
  return new Promise((resolve, reject) => {
    doSomething(foo, resolve, reject);
  });
};

If promisify.custom is defined but is not a function, promisify() will throw an error.