Javascript / Typescript如何并行运行异步函数?

时间:2019-01-20 19:20:27

标签: javascript typescript promise async-await

我有一段代码可以运行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)  

但是没有人成功加载。

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您正在寻找

[this.groupsLevels, this.indicators, this.sources, this.storeGroups] = await Promise.all([
  this.groupsLevelsService.getData(),
  this.configurationService.getIndicators(),
  this.configurationService.getSources(),
  this.storeGroupsService.getStoreGroups(),
]);

console.log(this.groupsLevels);
console.log(this.indicators);
console.log(this.sources); 
console.log(this.storeGroups);