Home > Software engineering >  How to handle multiple Axios calls in Javascript?
How to handle multiple Axios calls in Javascript?

Time:01-10

I am building an application in which, I am sending 3 axios calls concurrently from frontend to the backend by using axios.all function that make changes in a MONGO DB database. But the problem is, I want to send these axios requests in such a way that either all the 3 requests are made successfully, or if any 1 of the 3 fails, no other request call should be made. How can I do so in javascript?

let one = "request link 1";
let two = "request link 2";
let three = "request link 3";

const requestOne = axios.post(one, newInventory);
const requestTwo = axios.post(two, element);

const requestThree = axios.post(three, newObj);
axios.all([requestOne,requestTwo,requestThree]).then(axios.spread((...response)=>{
    alert("changes are made successfully");
    window.location.reload();
})).catch(err=>{
    alert("Some error has occured", err);
})

Here is the code. I am making 3 requests (requestOne, requestTwo, requestThree). Lets consider a case when the requestOne fails dues to some reason, while requestTwo and requestThree are successful. This is what I want to prevent. If any of the request fails, I want to revert the changes made by all the other successful requests. I want either all the requests to be successful, or all the requests to fail.

CodePudding user response:

axios.all and axios.spread are deprecated, and this is mentioned on their GitHub page as well. Here's the link: https://github.com/axios/axios#concurrency-deprecated. So, since it's deprecated, use Promise.all instead. Below is your code with Promise.all implemented

let one = "request link 1";
let two = "request link 2";
let three = "request link 3";

const requestOne = axios.post(one, newInventory);
const requestTwo = axios.post(two, element);
const requestThree = axios.post(three, newObj);

Promise.all([requestOne,requestTwo,requestThree]).then((res)=>{
    alert("changes are made successfully");
    window.location.reload();
})).catch(err=>{
    alert("Some error has occured", err);
})

Only an error will be returned if any of the promises get rejected otherwise it will return the responses of all promises. However, a rejection of any of the promises will not make other promises' request to stop, as the request fires concurrently in Promise.all.

  • Related