Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple fetch() in Promise.all - which one failed?

If I have multiple fetch() calls within a Promise.all block, when one fails, it all fails. That's cool, I need them all to resolve.

However, how can I find which one actually failed?

In the following code, the catch errortells me:

TypeError: Failed to fetch`

which makes it impossible to construct an effective user error message should I choose to do so.

const goodUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
const badUrl = 'https://ajax.googleapis77.com/ajax/libs/jquery/2.1.3/jquery.min.js';
Promise.all([
    fetch(goodUrl),
    fetch(badUrl), /* will fail */
    fetch(goodUrl)
]).then(([response1, response2, response3]) => {
    console.log(response1);
    console.log(response2);
    console.log(response3);
}).catch((err) => {
    console.log(err);
});

Here's a fiddle (a snippet didn't play nice)

I have looked for duplicates, this is not one as the examples throw the same error

like image 471
StudioTime Avatar asked Nov 18 '25 02:11

StudioTime


1 Answers

You could just catch each of them individually and throw some custom errors like:

...
Promise.all([
    fetch(goodUrl).catch(err => {
        throw {url: goodUrl, err};
    }),
    fetch(badUrl).catch(err => {
       throw {url: badUrl, err};
    }),
    fetch(goodUrl).catch(err => {
       throw {url: goodUrl, err};
    })
])
...
like image 75
Nhor Avatar answered Nov 20 '25 16:11

Nhor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!