javascript - 使用 await 调用/申请/绑定(bind)

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

但是,当我尝试 depromisify 一个箭头函数时它不会工作,因为你不能绑定(bind)任何东西到它:

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

有解决办法吗?

最佳答案

没有。没有解决方案。箭头函数在这方面有点特殊。

这是来自 docs 的引述:

Two factors influenced the introduction of arrow functions: shorter functions and non-binding of this.

关于javascript - 使用 await 调用/申请/绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50357683/

相关文章:

javascript - 使用 Three.js 制作带孔的圆 Angular 盒

javascript - Node.js:即使将 allowHalfOpen 设置为 True,客户端也会与服务器断开连接

javascript - Leaflet map.RemoveLayer 不工作 - 未捕获类型错误 : Cannot read property '_removePath' of undefined

Javascript - 变形/动画 svg 路径数据,无需 SMIL 或库

javascript - 异步发布和订阅消息在 pubnub 中不起作用

javascript - 多个 socket.io 客户端连接不起作用(Google Chrome、Firefox)

javascript - 创建一个效果以使元素淡入和淡出,而不使用 fadeToggle()

javascript - 访问 socket.io 回调函数外部的变量

node.js - 全局/命令行 Node.js 工具的配置位置

node.js - (不)将局部变量传递给 Express (node.js) 中的 Jade 模板