axios.get().then() 在 for 循环中 [英] 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 => {
// do something with response
users.push(response);
})
));
return users;
}
// some other async context
console.log(await getMultiple({ id: 'asdf'}, { id: 'foo' }, { id: 'bar' }));
这篇关于axios.get().then() 在 for 循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!