简体   繁体   English

axios 请求并行

[英]Axios requests in parallel

I had a question days ago, let's imagine we have the following 3 promises:几天前我有一个问题,假设我们有以下 3 个承诺:

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.它们将异步执行并使用.then()返回数据,假设每个 GET 请求需要 1.00 秒。

The total execution of this requests will take 3 seconds right?此请求的总执行将需要 3 秒对吧? Is there any way to execute this requests in parallel so that we get the data of the 3 requests in 1 second?有没有办法并行执行这个请求,以便我们在 1 秒内获得 3 个请求的数据? Or it's impossible because of the single-threaded language?还是因为单线程语言而不可能?

Thank you.谢谢你。

As of May 27, 2020 , you should use Promise.all :2020 年 5 月 27 日起,您应该使用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.allaxios.spread结合使用:

axios.all([axios.get(URL1), axios.get(URL2), axios.get(URL3)])
     .then(axios.spread(url1resp, url2resp, url3resp) {
          // do something
     });

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.虽然 JavaScript 在单个事件循环上运行(除非您使用 Workers),但异步代码不受该循环的约束。 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.发出 HTTP 请求的责任被移交给事件循环之外的代码。 This means it can execute in parallel.这意味着它可以并行执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM