等待通过 call 调用的异步函数或通过 Babel 应用

Await on an async function called with call or apply with Babel

如何 await 调用 callapplyBabel 调用的 async 函数?

下面是一个示例,其中 getOrdersService class 的 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

您可以尝试这样的包装器:

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

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

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

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

From the OP:

The problem was that let stream = service.getOrders.call(this, arg1, arg2, arg3); was in an anonymous function inside a regular function. Instead of marking anonymous function async, I did it for a regular function causing Babel SyntaxError: Unexpected token.

Thanks to to the solution.