Someimtes it can be usefull to do banch of tasks in "parallel" and do not stop if some of them has been finished with the error
Promise.all([
Promise.resolve(33).then((d) => { throw new Error(d)} ).catch(e => console.error('Inside ' + e)),
Promise.resolve('test')
]).then(result => console.log(result)).catch(e => console.error(e));
In the output we will see
> Inside Error: 33
[ undefined, 'test' ]
Although one of promises returned the error, others kept working.
Without handling the error right there in the first Promise we would end up with the following picture:
Error: Error: 33
at Promise.all.Promise.resolve.then (repl:2:41)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)
And we would never catch into latest .then() because Promise.all
waits for all fulfillments (or the first rejection).
Another advanced approach which I've used for fetching the web pages even though some of the requests could return timeout as a respone was the following:
const fetch = (url) => {
return node-fetch(url)
.then(result => result.json())
.catch((e) => {
return new Promise((resolve) => setTimeout(() => resolve(fetch(url)), timeout));
});
};
tasks = [fetch(url1), fetch(url2) ....];
Promise.all(tasks).then(......)
Here we use the same approach as above but in catch
we return another promise which we're trying to resolve recursively calling fetch
function within the time (setTimeout).