Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 231
krl Avatar asked Jun 17 '15 14:06

krl


1 Answers

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);
}
like image 130
loganfsmyth Avatar answered Sep 20 '22 08:09

loganfsmyth