Reputation: 8548
It may be that my question title is off, in case the promise.all
is not what I need to solve this issue.
I have a then()
- chain in my promise and I have a series of similar operations that I really should handle differently, but I am new to promises.
return new Promise(function(resolve, reject) {
c.scraper.load().then(function () {
....
var personUrl = url + "/" + c.people[0];
return c.checkPerson(personUrl);
}).then(function(){
var personUrl = url + "/" + c.people[1];
return c.checkPerson(personUrl);
}).then(function(){
var personUrl = url + "/" + c.people[2];
return c.checkPerson(personUrl);
....
I think you get the problem.
The first step would be to combine these three into one, and the second step, if possible, would be to make it work with an unknown number of people in the array c.people
.
Upvotes: 1
Views: 10624
Reputation: 4542
First, since c.scraper.load()
itself returns a promise, you can return the result of the entire promise chain, and you don't need to wrap it in new Promise(...)
.
Next, since c.people
seems to be an array of paths you want to fetch, you can map
the array to a list of promises, then use Promise.all()
to wait for them all to resolve:
return c.scraper.load().then(function () {
return Promise.all(c.people.map(function (person) {
var personUrl = url + "/" + person;
return c.checkPerson(personUrl);
}));
}).then(function (results) {
// `results` is an array containing the results of the `checkPerson()` calls
});
Does that help?
Upvotes: 3
Reputation: 4681
Assuming c.checkPerson
returns a Promise, you can do something like this:
var promiseArray = c.people.map(function(person) {
var personUrl = url + "/" + person;
return c.checkPerson(personUrl)
})
Promise.all(promiseArray).then(function() {
// complete
})
Upvotes: 2