用await调用/ apply/bind

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)

这有解决方案吗?

Ran*_*urn 5

不。没有解决方案。箭头功能在这方面有点特殊。

这是来自docs的报价:

有两个因素影响了箭头功能的引入:功能较短和对此功能没有约束力。