How to post multiple Axios requests at the same time?

54,517

Solution 1

There are three cases via you can achieve your goal.

  1. For simultaneous requests with Axios, you can use Axios.all()

     axios.all([
       axios.post(`/my-url`, {
         myVar: 'myValue'
       }), 
       axios.post(`/my-url2`, {
         myVar: 'myValue'
       })
     ])
     .then(axios.spread((data1, data2) => {
       // output of req.
       console.log('data1', data1, 'data2', data2)
     }));
    
  2. you can use Promise.allSettled(). The Promise.allSettled() method returns a promise that resolves after all of the given promises have either resolved or rejected,

  3. You can try to use Promise.all() but it has the drawback that if any 1 req failed then it will fail for all and give o/p as an error(or in catch block)

but the best case is the first one.

Solution 2

For simultaneous requests with Axios you can use Axios.all().

axios.all([
  axios.get('https://api.github.com/users/MaksymRudnyi'), 
  axios.get('https://api.github.com/users/taylorotwell')
])
.then(axios.spread((obj1, obj2) => {
  // Both requests are now complete
  console.log(obj1.data.login + ' has ' + obj1.data.public_repos + ' public repos on GitHub');
  console.log(obj2.data.login + ' has ' + obj2.data.public_repos + ' public repos on GitHub');
}));

Also, you can use Promise.all(). Works similar:

Promise.all([
  fetch('https://api.github.com/users/MaksymRudnyi'),
  fetch('https://api.github.com/users/taylorotwell')
])
.then(async([res1, res2]) => {
  const a = await res1.json();
  const b = await res2.json();
  console.log(a.login + ' has ' + a.public_repos + ' public repos on GitHub');
  console.log(b.login + ' has ' + b.public_repos + ' public repos on GitHub');
})
.catch(error => {
  console.log(error);
});

But, with Promise.all() there is a specific behavior. In case at least one request will be rejected - the all request will be rejected and code will go to .catch() sections. It's OK in case you need to be sure that all requests are resolved.

In case when it's OK when some of your requests are rejected consider using Promise.allSettled(). The Promise.allSettled() method returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describes the outcome of each promise.

Solution 3

Try this with Axios.all and

  • Use Promise.all() method returns a single Promise that fulfills when all of the promises passed as an iterable have been fulfilled Promise MDN ref Link

    import axios from 'axios';
    let one = "https://api1"
    let two = "https://api2"
    let three = "https://api3"
    
    const requestOne = axios.get(one);
    const requestTwo = axios.get(two);
    const requestThree = axios.get(three);
    
    axios.all([requestOne, requestTwo, requestThree]).then(axios.spread((...responses) => {
      const responseOne = responses[0]
      const responseTwo = responses[1]
      const responesThree = responses[2]
      // use/access the results 
    console.log("responseOne",responseOne);
    console.log("responseTwo",responseTwo);
    console.log("responesThree",responesThree);
    })).catch(errors => {
      console.log(errors);
    })
    

Ref Link

Find full example here for axios

Solution 4

Try in this way

window.axios.all([requestOne, requestTwo, requestThree])
  .then(axios.spread((...responses) => {
    const responseOne = responses[0]
    const responseTwo = responses[1]
    const responesThree = responses[2]
    // use/access the results 
  })).catch(errors => {
    // react on errors.
  })

Solution 5

If you want to have it within a loop, you can have slightly modified version of @deelink as below

let promises = [];
for (i = 0; i < 10; i++) {
  promises.push(
    window.axios.post(`/my-url`, {
    myVar: 'myValue'})
   .then(response => {
      // do something with response
    })
  )
}

Promise.all(promises).then(() => console.log('all done'));
Share:
54,517
Z0q
Author by

Z0q

Updated on February 03, 2022

Comments

  • Z0q
    Z0q over 2 years

    At this moment I have a webpage in which a long list of Axios POST calls are being made. Now, the requests seem to be sent in parallel (JavaScript continues sending the next request before the result is received).

    However, the results seem to be returned one by one, not simultaneously. Let's say one POST call to the PHP script takes 4 seconds and I need to make 10 calls. It would currently take 4 seconds per call, which would be 40 seconds in total. I hope to find a solution to both and receive all results at approximately the same time (~4 seconds) instead of ~40 seconds.

    Now I've read about threads, multithreading in NodeJS using Workers. I've read that JavaScript itself is only single-threaded, so it may not allow this by itself.

    But I'm not sure where to go from here. All I have are some ideas. I'm not sure whether or not I'm heading into the right direction and if I am, I am not sure how to use Workers in NodeJS and apply it in my code. Which road should I take? Any guidance would be highly appreciated!

    Here is a small piece of example code:

    for( var i = 0;  i < 10;  i++ )
    {
        window.axios.post(`/my-url`, {
            myVar: 'myValue'
        })
        .then((response) => {
            // Takes 4 seconds, 4 more seconds, 4 more seconds, etc
            // Ideally: Takes 4 seconds, returns in the same ~4 seconds, returns in the same ~4 seconds, etc
            console.log( 'Succeeded!' );
        })
        .catch((error) => {
            console.log( 'Error' );
        });
    
        // Takes < 1 second, < 1 more second, < 1 more second, etc
        console.log( 'Request sent!' );
    }