自定义 promise 化函数


【Custom promisified functions】

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

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

import { promisify } from 'node:util';

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

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

const promisified = promisify(doSomething);
console.log(promisified === doSomething[promisify.custom]);
// prints 'true'const { promisify } = require('node:util');

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

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

const promisified = promisify(doSomething);
console.log(promisified === doSomething[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.】

例如,对于一个接收 (foo, onSuccessCallback, onErrorCallback) 的函数:

【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);
  });
}; 

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

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