自定义 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.