【问题标题】:Await on an async function called with call or apply with Babel等待调用调用的异步函数或使用 Babel 应用
【发布时间】:2015-06-17 14:18:24
【问题描述】:

我如何在async 上使用callapplyBabel 调用函数上的await

下面是一个示例,其中getOrdersService 类的async 方法:

class Service() {
   async getOrders(arg1, arg2, arg3) {
      return await this.anotherService.getOrders(arg1, arg2, arg3);
   }
}

let service = new Service();
// ...
// Babel doesn't compile 
// let stream = await service.getOrders.call(this, arg1, arg2, arg3);
// producing SyntaxError: Unexpected token for await
let stream = service.getOrders.call(this, arg1, arg2, arg3);
stream.pipe(res); // obviously not working without await in the prev line

【问题讨论】:

  • 当您想在另一个异步函数之外调用一个异步函数时,您是否在问该怎么做?目前尚不清楚这与调用/应用/绑定有什么关系,或者您在问题中传递给 callthis 是什么。
  • @loganfsmyth 不,我在问如何在 async 函数上使用 await callapply
  • 你会像往常一样使用 await 。更新了我的答案。
  • @loganfsmyth call 不是async 函数(尽管在这种情况下它调用了async 函数),所以这里的await 不起作用。至少目前是babel
  • await 只是接受一个承诺。例如var streamPromise = service.getOrders(); var stream = await streamPromise;。您使用 call 的事实只会改变您调用 getOrders 的方式,它不会影响 await 的工作方式。如果您有一个不起作用的特定示例,请将其添加到您的问题中。

标签: javascript async-await babeljs ecmascript-next


【解决方案1】:

async function 返回一个 Promise,await 接受一个 Promise。不需要通过 await 调用所有 async 函数。如果你想在标准 JS 函数中使用异步函数,你可以直接使用 result 承诺。在您的情况下,使用 .call 调用函数仍然会像任何其他函数一样返回一个 Promise,因此您应该将该 Promise 传递给 await:

async function doThing(){
  let service = new Service();

  var stream = await service.getOrders.call(this, arg1, arg2, arg3)
  stream.pipe(res);
}

【讨论】:

  • 这是我所期望的,但babel 目前似乎不支持它。
  • 请提供一个在 Babel 中演示的示例,因为它肯定也应该在那里工作。您当前的示例甚至没有使用 await。
  • 因为babel 不能编译let stream = await service.getOrders.call(this, arg1, arg2, arg3);。为await 提供SyntaxError: Unexpected token
  • 您也必须将 await 放入异步函数中。这就是为什么我问“当你想在另一个异步函数之外调用一个异步函数时,你问该怎么做?”上面,你说不。
  • getOrdersasync 并且确实有 await
【解决方案2】:

From the OP:

问题在于let stream = service.getOrders.call(this, arg1, arg2, arg3); 位于常规函数内的匿名函数中。我没有标记匿名函数 async,而是为一个导致 Babel SyntaxError: Unexpected token 的常规函数​​这样做。

感谢@loganfsmyth for leading me的解决方案。

【讨论】:

    【解决方案3】:

    你可以试试这样的包装器:

    class Service() {
       async getOrders(arg1, arg2, arg3) {
       // ....
       };
       wrappedOrders(arg1, arg2, arg3) {
           let res = await getOrders(arg1, arg2, arg3);
           return res;
       }
    }
    

    并以这种方式调用 WrappedOrders:

    let stream = service.wrappedOrders.call(this, arg1, arg2, arg3);
    

    【讨论】:

    • 每个带有await 的函数都是async,所以wrappedOrders 也必须是async,这让我们回到我的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    相关资源
    最近更新 更多