【问题标题】:Javascript/Typescript How to run async functions in parallel? [duplicate]Javascript/Typescript 如何并行运行异步函数? [复制]
【发布时间】: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


【解决方案1】:

你正在寻找

[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);

【讨论】:

  • 太棒了。我从来没有见过这个符号[x,y,z] = ...是什么意思?它是哪个 ES 的一部分?
  • @DanielSantos 这是数组解构,从 ES6 开始可用。更常用于变量声明,但您可以在元素中使用任何目标表达式:-)
猜你喜欢
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-08
相关资源
最近更新 更多