Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

javascript - 呼叫/应用/绑定与等待[重复](Call/apply/bind with await [duplicate])

I have to work with a callback based API, but I would like to retain my async functions.(我必须使用基于回调的API,但我想保留我的异步功能。)

That's why I'm trying to write a depromisify function:(这就是为什么我要编写一个取消分配功能的原因:)

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

However it won't work when I try to depromisify an arrow function, as you can't bind anything to it:(但是,当我尝试取消对箭头功能的限制时,它将无法工作,因为您无法将任何内容绑定到它:)

new Usual(depromisify(async () => {
  this.hello();
  return false;
}));

Is there a solution for this?(有解决方案吗?)

  ask by Misiur translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Nope.(不。)

No solution.(没有解决方案。) Arrow functions are a bit special in that regard.(箭头功能在这方面有点特殊。)

Here is the quote from the docs :(这是来自docs的报价:)

Two factors influenced the introduction of arrow functions: shorter functions and non-binding of this.(有两个因素影响了箭头功能的引入:功能较短和对此功能没有约束力。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...