use*_*677 15 javascript promise axios
我将如何在 for 循环中运行 Axios,每个循环都有相应的.then()函数。然后在 for 循环结束后,运行另一个函数。
例子:
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);
Run Code Online (Sandbox Code Playgroud)
Dan*_*ema 31
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));
Run Code Online (Sandbox Code Playgroud)
.then()Promise 本身的方法返回一个 Promise;所以你可以收集这些并用Promise.all().
请注意,即使您在一个async函数中执行此操作,您也不希望await在 for 循环内,因为每个请求将在它开始之前等待前一个完成,并且大概您想运行这些请求在平行下。
根据您的用例,简洁的 async / await 函数可能如下所示:
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' }));
Run Code Online (Sandbox Code Playgroud)
小智 6
如果您使用的是受支持的较新版本的 javascript async/await,您可以执行以下操作:
const array = ['asdf', 'foo', 'bar'];
let users = [];
for (const id in array) {
const response = await axios('/user/' + id);
users.push(response);
}
console.log(users);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18324 次 |
| 最近记录: |