1

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.

CupawnTae
  • 14,192
  • 3
  • 29
  • 60
Matt Welander
  • 8,234
  • 24
  • 88
  • 138
  • 1
    Avoid the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572)! – Bergi Feb 02 '16 at 23:56
  • Don't forget `.catch(e => console.error(e));` at the end so you can see if you make an error! – jib Feb 03 '16 at 07:36

2 Answers2

3

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?

btmills
  • 4,431
  • 24
  • 22
  • 1
    @Freyday below is correct that this approach only works if `c.checkPerson()` returns a promise. – btmills Feb 02 '16 at 23:04
  • Or `c.scraper.load().then(() => Promise.all(c.people.map(person => c.checkPerson(url + "/" + person)))).then(results => {}).catch(e => console.error(e));` – jib Feb 03 '16 at 07:44
2

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
})
mikefrey
  • 4,653
  • 3
  • 29
  • 40