for循环中的Axios.get().then() [英] Axios.get().then() in a for loop
问题描述
我将如何在for循环中运行Axios,每个循环都具有相应的.then()
函数.然后在for循环结束后,运行另一个函数.
How would I go about running Axios in a for loop, each with a corresponding .then()
function. Then after the for loop ends, run another function.
示例:
const array = ['asdf', 'foo', 'bar'];
let users = [];
for (i = 0; i < array.length; i++) {
axios.get('/user/' + array[i].id).then(response => {
// do something with response
users.push(response);
});
}
console.log(users);
推荐答案
const array = [{ id: 'asdf'}, { id: 'foo' }, { id: 'bar' }]; // changed the input array a bit so that the `array[i].id` would actually work - obviously the asker's true array is more than some contrived strings
let users = [];
let promises = [];
for (i = 0; i < array.length; i++) {
promises.push(
axios.get('/user/' + array[i].id).then(response => {
// do something with response
users.push(response);
})
)
}
Promise.all(promises).then(() => console.log(users));
Promise本身的.then()
方法返回Promise;这样您就可以收集这些内容并通过Promise.all()
等待所有这些内容.
The .then()
method of a Promise itself returns a Promise; so you can collect those and await all of them with Promise.all()
.
请注意,即使您是在async
函数中执行此操作,也不想在for循环内使用await
,因为这样每个请求都将等待上一个请求完成才开始,大概是您希望并行运行这些请求.
Note that even if you're doing this within an async
function, you don't want to await
inside the for-loop, because then each request will wait for the previous one to finish before it even starts, and presumably you want to run these requests in parallel.
根据您的用例,简洁的async/await函数可能看起来像这样:
Depending on your use case, a concise async / await function might look like this:
async function getMultiple(...objectsToGet) {
let users = [];
await Promise.all(objectsToGet.map(obj =>
axios.get('/user/' + obj.id).then(response => {
users.push(response);
})
));
return users;
}
// some other async context
console.log(await getMultiple({ id: 'asdf'}, { id: 'foo' }, { id: 'bar' }));
这篇关于for循环中的Axios.get().then()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!