Wednesday, 26 April 2017

Catching promise errors from a loop

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?



via user99999

No comments:

Post a Comment