我有一个非常大的 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.
关于javascript - 公理 : How to run multiple requests one after the other?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62628829/