gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:21:11 33 4
gpt4 key购买 nike

我有一个非常大的 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 untilall of them are ready.

For instance, download several URLs in parallel and process thecontent 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com