Axios requests in parallel

末鹿安然 提交于 2020-05-17 08:28:19

问题


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.


回答1:


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
     });



回答2:


The code you have will execute them in parallel. That's the point of asynchronous functions.

While JavaScript runs on a single event loop (unless you use Workers), asynchronous code is not bound by that loop. That's why the code is asynchronous in the first place.

The responsibility for making the HTTP requests is handed off to code outside of the event loop. This means it can execute in parallel.



来源:https://stackoverflow.com/questions/57066137/axios-requests-in-parallel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!