Axios:如何一个接一个地运行多个请求? [英] Axios : How to run multiple requests one after the other?

查看:34
本文介绍了Axios:如何一个接一个地运行多个请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的 ID 数组(数千个 ID).我想遍历这个数组,对于每个值,像这样向 API 发出请求:

[12, 32, 657, 1, 67, ...].forEach((id) => {axios.get(`myapi.com/user/${id}`).then(({ data }) => {控制台日志(数据名称);});});

但是,我有很多请求要发出,我无法使它们异步,因为我的计算机有限制...是否可以等待每个请求完成后再发出下一个请求?

解决方案

不要在 id 中使用 forEach 尝试 Promise.all

const ids = [12, 32, 657, 1, 67];const promises = ids.map((id) => axios.get(`myapi.com/user/${id}`));Promise.all([...promises]).then(function (values) {控制台日志(值);});

<块引用>

假设我们希望多个 promise 并行执行并等待他们都准备好了.

例如,并行下载多个 URL 并处理全部完成后的内容.

来自 https://javascript.info/promise-api

I have a very large array of IDs (thousands of IDs). I want to loop through this array and for each value, make a request to an API like so :

[12, 32, 657, 1, 67, ...].forEach((id) => {
    axios.get(`myapi.com/user/${id}`).then(({ data }) => {
        console.log(data.name);
    });
});

However, I have so many requests to make I can't make them asynchronous because my computer has limits... Is it possible to wait for each request to be finished before making the next one ?

解决方案

Instead of using forEach in id try Promise.all

const ids = [12, 32, 657, 1, 67];
const promises = ids.map((id) => axios.get(`myapi.com/user/${id}`));

Promise.all([...promises]).then(function (values) {
  console.log(values);
});

Let’s say we want many promises to execute in parallel and wait until all of them are ready.

For instance, download several URLs in parallel and process the content once they are all done.

From https://javascript.info/promise-api

这篇关于Axios:如何一个接一个地运行多个请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆