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, andawait
accepts a promise. There is no requirement that allasync
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: