<分区>
我必须使用基于回调的 API,但我想保留我的异步函数。这就是为什么我要尝试编写 depromisify 函数:
const depromisify = fn => {
if (!(fn[Symbol.toStringTag] === 'AsyncFunction')) {
return fn;
}
// Can be `async` as the caller won't use assignment to get the result - it's all bound to the `cb`
return async function () {
const args = [...arguments];
const cb = args.pop();
try {
return cb(null, await fn.apply(this, args));
} catch (e) {
return cb(e);
}
};
};
const normal = function(cb) {
this.hello();
cb(null, true);
};
const promised = async function() {
this.hello();
return true;
};
function Usual(fn) {
this.random = 'ABC';
fn.call(this, (err, result, info) => {
console.log((err && err.message) || null, result);
});
};
Usual.prototype.hello = () => {
console.log('hello!');
};
new Usual(normal);
new Usual(depromisify(promised));
但是,当我尝试 depromisify 一个箭头函数时它不会工作,因为你不能绑定(bind)任何东西到它:
new Usual(depromisify(async () => {
this.hello();
return false;
}));
有解决办法吗?