简体   繁体   中英

Catching individual errors when using Fetch API

I'm trying to make multiple fetch calls at once, so far I've used this page to reach a point where I can make multiple calls correctly. However the problem now is if one of those calls returns an error. What I'd like, is that if one URL is good and one is bad, the good URL still returns the JSON object, but the bad URL returns the error. But the catch statement notices one error and stops both calls.

My current code:

let resList = await Promise.all([
    fetch(goodURL),
    fetch(badURL)
]).then(responses => {
    return Promise.all(responses.map(response => {
        return response.json();
    }))
}).catch(error => {
    console.log(error);
});

console.log(resList);

Currently, logging resList returns undefined when I want it to return the JSON object from the good URL

As @jonrsharpe mentioned, .allSettled() is probably your best bet.

You can also basically make your own version with something like this:

const results = await Promise.all(
  [a, b, c].map(p => 
    p.catch(err => { 
      /* do something with it if you want */ 
    }
  )
);

Basically, instead of having one catch on Promise.all() , you attach a catch to each Promise BEFORE giving it to Promise.all() . If one of them throws an error, it'll trigger its individual catch, which you can do whatever with. As long as you don't return something else, you'll end up with it returning undefined , which you can filter out.

For example, if a and c worked and b errored, your results would look like this:

['a', undefined, 'b']

And it'd be in the same order as you fed the promises in, so you could tell which was the failure.

 const a = new Promise((resolve) => setTimeout(() => resolve('a'), 100)); const b = new Promise((_, reject) => setTimeout(() => reject('b'), 200)); const c = new Promise((resolve) => setTimeout(() => resolve('c'), 50)); (async () => { const results = await Promise.all( [a, b, c].map(p => p.catch(err => console.error('err', err)) ) ); console.log(results); })();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM