Wil*_*aiz 5 javascript node.js axios
几天前我有一个问题,让我们假设我们有以下 3 个承诺:
let promise1 = axios.get(URL1);
let promise2 = axios.get(URL2);
let promise3 = axios.get(URL3);
Run Code Online (Sandbox Code Playgroud)
它们将异步执行并使用 返回数据.then(),假设每个 GET 请求需要 1.00 秒。
此请求的总执行将需要 3 秒,对吗?有没有办法并行执行这些请求,以便我们在 1 秒内获得 3 个请求的数据?还是因为单线程语言是不可能的?
谢谢你。
自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
});
Run Code Online (Sandbox Code Playgroud)
现在已弃用:您可以axios.all结合使用axios.spread:
axios.all([axios.get(URL1), axios.get(URL2), axios.get(URL3)])
.then(axios.spread(url1resp, url2resp, url3resp) {
// do something
});
Run Code Online (Sandbox Code Playgroud)
您拥有的代码将并行执行它们。这就是异步函数的意义所在。
虽然 JavaScript 在单个事件循环上运行(除非您使用 Workers),但异步代码不受该循环的约束。这就是为什么代码首先是异步的。
发出 HTTP 请求的责任移交给事件循环之外的代码。这意味着它可以并行执行。
| 归档时间: |
|
| 查看次数: |
4992 次 |
| 最近记录: |