简体   繁体   中英

A query on sending multiple requests using Axios - React

There is a scenario where I need to call multiple services at once using Axios and I need to consider values for success API calls and neglect the failed API calls. For example, see the case below:

let URL1 = "https://www.something.com"
let URL2 = "https://www.something1.com"
let URL3 = "https://www.something2.com"

const promise1 = axios.get(URL1);  // SUCCESS
const promise2 = axios.get(URL2);  // SAY THIS SERVICE CALL WAS FAILED SENDING 404 ERROR
const promise3 = axios.get(URL3);  // SUCCESS

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
}).catch((e)=>{ console.log("error",e)});

Say the Service 2 was failed while service 1 and 3 are succeeded, in such case the promise chain getting broken and throwing the error. I gonna need the output in such case as [response_1, null, response_3] . Can you please guide me in how to achieve this? Thanks in advance.

My guess is that you should manually implement it by returning Promise.resolve() on catch .

let URL1 = "https://www.something.com"
let URL2 = "https://www.something1.com"
let URL3 = "https://www.something2.com"

const promise1 = axios.get(URL1).catch(() => Promise.resolve());  // SUCCESS
const promise2 = axios.get(URL2).catch(() => Promise.resolve());  // SAY THIS SERVICE CALL WAS FAILED SENDING 404 ERROR
const promise3 = axios.get(URL3).catch(() => Promise.resolve());  // SUCCESS

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
}).catch((e)=>{ console.log("error",e)});

This way, if an axios request fail, it will first get in axios.catch then return a success with whatever value you need.

You can find more informations about Promise chaining on MDN Using Promises Chaining ( like chaining after a catch ).

Promise.all() will not see any catch, so keep in mind those request will no longer be able to fail on Promise.all .

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