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

8.6k views Asked by At

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
3

There are 3 answers

7
loganfsmyth On BEST ANSWER

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);
}
1
pinturic On

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);
0
JDB On

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.