简体   繁体   中英

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

How do I await on async function called with call or apply with Babel ?

Below is an example, where getOrders is an async method of a Service class:

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

An async function returns a Promise, and await accepts a promise. There is no requirement that all async functions be called via await. If you want to use an async function inside a standard JS function, you would directly use the result promise. In your case, calling a function with .call will still return a promise like any other function, so you'd they pass that promise to 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 @loganfsmyth for leading me to the solution.

You can try a wrapper like this:

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

and call the wrappedOrders this way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM