Mis*_*iur 6 javascript node.js
我必须使用基于回调的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));Run Code Online (Sandbox Code Playgroud)
但是,当我尝试去除箭头函数时,它将无法工作,因为您无法绑定任何内容:
new Usual(depromisify(async () => {
this.hello();
return false;
}));
Run Code Online (Sandbox Code Playgroud)
这有解决方案吗?
| 归档时间: |
|
| 查看次数: |
1143 次 |
| 最近记录: |