javascript - 公理 : How to run multiple requests one after the other?

标签 javascript api asynchronous axios

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

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

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

最佳答案

不要在 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) {
  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.

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

关于javascript - 公理 : How to run multiple requests one after the other?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62628829/

相关文章:

c# - 我在哪里可以找到异步队列的当前内容?

javascript - 我可以在 <option> 标签中传递多个值吗?

javascript - JavaScript 中的数组乘法

mysql - 有没有办法从 Ruby-on-Rails 模型中获取数据库中的数据

api - Twitter Account Activity API - 如何为事件订阅 webhook?

c# - 在 C# 构造函数中等待 AsyncMethod

javascript - AngularJS:多个异步调用 - 如何

javascript - 我将如何自动化这个红绿灯序列?

javascript - Firefox 点击事件错误

android - 我可以通过 Smack 在我的好友列表中获取在线用户吗?