1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.