这是我的 forEach 循环。如何在循环完成后立即调用语句?我无法弄清楚
array.forEach(item => {
console.log("Loop started");
let id = [item.id];
let type = item.type;
if (subType == "a") {
api.method(type, id)
.then(response => {
console.log("response.data :>> ", response.data);
})
.finally(() => {
console.log("finally item :>> ", item);
});
} else if (subType == "b") {
api.method(type, id)
.then(response => {
console.log("response.data :>> ", response.data);
})
.finally(() => {
console.log("finally item :>> ", item);
});
}
});
最佳答案
由于 axios 调用返回 promise 。你能做的就是等待所有的 promise 完成。
let jobs: Promise<any>[] = [];
array.forEach(item => {
console.log("Loop started");
let id = [item.id];
let type = item.type;
if (subType == "a") {
const job = api.method(type, id)
.then(response => {
console.log("response.data :>> ", response.data);
})
.finally(() => {
console.log("finally item :>> ", item);
});
jobs.push(job);
} else if (subType == "b") {
const job = api.method(type, id)
.then(response => {
console.log("response.data :>> ", response.data);
})
.finally(() => {
console.log("finally item :>> ", item);
});
jobs.push(job)
}
});
await Promise.all(jobs);
// the code here will start to execute when all promises have been resolved.
关于javascript - 如何在完成具有 axios 调用的 for/forEach 循环执行后调用语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61579417/