0

I have a piece of code which runs 4 async functions:

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

How Can I run all of 4 in parallel ? and get the final result when all of them is done.?

I tried

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)  

But no one was loaded successfully.

what am I doing wrong?

Daniel Santos
  • 14,328
  • 21
  • 91
  • 174
  • 1
    Your question has already been answered [here](https://stackoverflow.com/questions/35612428/call-async-await-functions-in-parallel). :) – Sebastian Waldbauer Jan 20 '19 at 19:22
  • the answer that you quote does not returns a value. – Daniel Santos Jan 20 '19 at 19:24
  • 1
    Take as a side note that JS is single threaded and _async_ does not mean _in parallel_ – Igor Chernega Jan 20 '19 at 19:25
  • 2
    [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) returns a promise. So you can use ```.then(() => { })```. You can pass your data to variables and after your then you can access those variables. – Sebastian Waldbauer Jan 20 '19 at 19:26

1 Answers1

2

You are looking for

[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);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Great. I never seen this notation `[x,y,z] = ...` What does it means? It is part of which ES ? – Daniel Santos Jan 20 '19 at 22:16
  • 1
    @DanielSantos It's array destructuring, available since ES6. More commonly used with variable declarations, but you can use any target expression in the elements :-) – Bergi Jan 20 '19 at 22:20