【发布时间】:2015-06-17 14:18:24
【问题描述】:
我如何在async 上使用call 或apply 和Babel 调用函数上的await?
下面是一个示例,其中getOrders 是Service 类的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
【问题讨论】:
-
当您想在另一个异步函数之外调用一个异步函数时,您是否在问该怎么做?目前尚不清楚这与调用/应用/绑定有什么关系,或者您在问题中传递给
call的this是什么。 -
@loganfsmyth 不,我在问如何在
async函数上使用awaitcall或apply。 -
你会像往常一样使用 await 。更新了我的答案。
-
@loganfsmyth
call不是async函数(尽管在这种情况下它调用了async函数),所以这里的await不起作用。至少目前是babel。 -
await只是接受一个承诺。例如var streamPromise = service.getOrders(); var stream = await streamPromise;。您使用 call 的事实只会改变您调用getOrders的方式,它不会影响await的工作方式。如果您有一个不起作用的特定示例,请将其添加到您的问题中。
标签: javascript async-await babeljs ecmascript-next