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?

4
  • 1
    Your question has already been answered here. :) Commented Jan 20, 2019 at 19:22
  • the answer that you quote does not returns a value. Commented Jan 20, 2019 at 19:24
  • 1
    Take as a side note that JS is single threaded and async does not mean in parallel Commented Jan 20, 2019 at 19:25
  • 2
    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. Commented Jan 20, 2019 at 19:26

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Great. I never seen this notation [x,y,z] = ... What does it means? It is part of which ES ?
@DanielSantos It's array destructuring, available since ES6. More commonly used with variable declarations, but you can use any target expression in the elements :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.