【发布时间】:2019-01-20 19:20:27
【问题描述】:
我有一段代码运行 4 个async 函数:
this.groupsLevels = await this.groupsLevelsService.getData();
this.indicators = await this.configurationService.getIndicators();
this.sources = await this.configurationService.getSources();
this.storeGroups = await this.storeGroupsService.getStoreGroups();
console.log(this.groupsLevels) // All of them is populated
console.log(this.indicators) // All of them is populated
console.log(this.sources) // All of them is populated
console.log(this.storeGroups) // All of them is populated
如何并行运行所有 4 个?并在全部完成后得到最终结果。?
我试过了
Promise.all([
async () => {this.groupsLevels = await this.groupsLevelsService.getData(); },
async () => {this.indicators = await this.configurationService.getIndicators(); },
async () => {this.sources = await this.configurationService.getSources(); },
async () => {this.storeGroups = await this.storeGroupsService.getStoreGroups(); },
]);
console.log(this.groupsLevels)
console.log(this.indicators)
console.log(this.sources)
console.log(this.storeGroups)
但是没有人加载成功。
我做错了什么?
【问题讨论】:
-
您的问题已被here 回答。 :)
-
你引用的答案没有返回值。
-
附带说明 JS 是单线程的,async 并不意味着 inparallel
-
Promise.all 返回一个承诺。所以你可以使用
.then(() => { })。您可以将数据传递给变量,然后您可以访问这些变量。
标签: javascript typescript promise async-await