代码之家  ›  专栏  ›  技术社区  ›  Daniel Santos

javascript/typescript如何并行运行异步函数?[复制品]

  •  0
  • Daniel Santos  · 技术社区  · 7 年前

    这个问题已经有了答案:

    我有一段代码运行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 回复  |  直到 7 年前
        1
  •  2
  •   Bergi    7 年前

    你在找

    [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);
    
    推荐文章