0

I need to call multiple promises inside a for loop, but it gives me unhandled promise exception during each run. The way to solve this is to return the second promise, this way the last catch would be executed and it would work without errors, but - second and more iterations would not be executed.

const doFirstThing = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (resolve(['a', 'b', 'c'])), 1000);
    });
}

const doSecondThing = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (reject('test')), 500); // reject here
    });
}

doFirstThing()
.then(results => {
    results.forEach(result => {
        doSecondThing(result)
        .then(() => console.log(result, 'done'));
    });
})
.catch(error => console.log(error));

How can I deal with this?

user99999
  • 1,994
  • 5
  • 24
  • 45
  • try putting a 'return' before your 'doSecondThing' and then the errors should flow up the then's, or so i believe. – C Smith Apr 26 '17 at 21:20
  • Yes, but it would return from the first iteration... – user99999 Apr 26 '17 at 21:20
  • yep youre right, use JQuery $.when or Promise.all and use your loop to create an array of promises to pass in. – C Smith Apr 26 '17 at 21:22
  • Yeah, have you tried https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all ? – mfirry Apr 26 '17 at 21:23
  • [Never use `forEach` with (or without) promises!](http://stackoverflow.com/a/37576787/1048572) – Bergi Apr 27 '17 at 00:44

1 Answers1

1

To prevent unhandled promise exception chain .catch() to lat .then(); substitute using Promise.all() and .map() for .forEach()

const doFirstThing = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (resolve(['a', 'b', 'c'])), 1000);
    })
}

const doSecondThing = (r) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (reject('test')), 500); // reject here
    })
}

doFirstThing()
.then(results => {
    return Promise.all(results.map(result => {
        return doSecondThing(result)
    }));
})
.then((result) => console.log(result, 'done'))
.catch(error => console.log(`err:${error}`));
guest271314
  • 1
  • 15
  • 104
  • 177
  • 1
    `.catch(err => Promise.reject(err));` [makes no sense](http://stackoverflow.com/q/41089122/1048572) – Bergi Apr 27 '17 at 00:45