1

I have the array as below:

arr = ['res1', 'res2', 'res3'];

Then for each arr value, I will do an API call that will return a promise

arr.forEach(val => this.getPromise(val));

The method getPromise returns a promise. I need to wait for all promises before i invoke another method. How should I do it?

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
iPhoneJavaDev
  • 821
  • 5
  • 33
  • 78
  • this moght be helpful https://daveceddia.com/waiting-for-promises-in-a-loop/ – Pratap A.K Sep 26 '18 at 02:45
  • https://stackoverflow.com/a/39890818/2742156 – Pratap A.K Sep 26 '18 at 02:47
  • First try building an array of promises, then using [Promise.all(arrayOfPromises)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) and see if that works for you. This way you can execute all in parallel. – Alexander Staroselsky Sep 26 '18 at 02:50

1 Answers1

4

You can use Promise.all() to perform an action after all promises have resolved. It takes an array of promises:

const promises = ["val1", "val2"].map(val => this.getPromise(val));

Promise.all(promises)
    .then(results => console.log(results)) // this is an array
    .catch(err => console.log(err));

You can use then() and catch() as you would with a promise. The response is an array of resolved values.

Hopefully that helps!

Jameel Moideen
  • 7,542
  • 12
  • 51
  • 79
Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91