Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios requests in parallel

I had a question days ago, let's imagine we have the following 3 promises:

let promise1 = axios.get(URL1);
let promise2 = axios.get(URL2);
let promise3 = axios.get(URL3);

They will execute asynchronously and return the data with .then(), and let's suppose each of these GET requests take 1.00 seconds.

The total execution of this requests will take 3 seconds right? Is there any way to execute this requests in parallel so that we get the data of the 3 requests in 1 second? Or it's impossible because of the single-threaded language?

Thank you.

like image 646
Will Paiz Avatar asked Jul 16 '19 22:07

Will Paiz


1 Answers

As of May 27, 2020, you should use Promise.all:

Promise.all([axios.get(URL1), axios.get(URL2), axios.get(URL3)])
    .then((responses) => {
        const [url1rest, url2resp, url3resp] = responses;
        // do something
    });

Now deprecated: you can use axios.all in conjunction with axios.spread:

axios.all([axios.get(URL1), axios.get(URL2), axios.get(URL3)])
     .then(axios.spread(url1resp, url2resp, url3resp) {
          // do something
     });
like image 96
dave Avatar answered Sep 28 '22 15:09

dave