admin管理员组文章数量:1393121
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/user/${id}`).then(({ data }) => {
console.log(data.name);
});
});
However, I have so many requests to make I can't make them asynchronous because my puter has limits... Is it possible to wait for each request to be finished before making the next one ?
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./user/${id}`).then(({ data }) => {
console.log(data.name);
});
});
However, I have so many requests to make I can't make them asynchronous because my puter has limits... Is it possible to wait for each request to be finished before making the next one ?
Share Improve this question asked Jun 28, 2020 at 22:20 tomfltomfl 7071 gold badge14 silver badges31 bronze badges3 Answers
Reset to default 3Instead of using forEach
in id try Promise.all
const ids = [12, 32, 657, 1, 67];
const promises = ids.map((id) => axios.get(`myapi./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
Let's assume that you allow n
requests to be sent maximum at any given time. For the sake of the example I assume it's 10:
var n = 10;
We also store the current index:
var index = 0;
Let's implement a function to handle the requests:
function req() {
axios.get(`myapi./user/${input[index]}`).then(({ data }) => {
console.log(data.name);
if (index + 1 < input.length) {
index++;
req();
}
});
}
Then, let's send the first n
requests:
while (index < n) {req(); index++}
Yes, index
is global, but it is global for the sake of readability.
Firstly, it's clear you have to redesign your api.
However, you can try:
Promise.all([12, 32, 657, 1, 67, ...].map((id) => {
return axios.get(`myapi./user/${id}`).then(({ data }) => {
console.log(data.name);
});
})).then(_=>console.log('done'));
or look into p-queue which will help you manage the queue of promises.
本文标签: javascriptAxiosHow to run multiple requests one after the otherStack Overflow
版权声明:本文标题:javascript - Axios : How to run multiple requests one after the other? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744755511a2623437.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论