iPhoneJavaDev
iPhoneJavaDev

Reputation: 825

Angular 5 wait for promises to return from for loop

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?

Upvotes: 1

Views: 486

Answers (1)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38767

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!

Upvotes: 4

Related Questions