如何在完成for/forEach循环执行后调用一条语句



这是我的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调用return 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.

我建议使用p迭代npm模块,它们为每个数组循环都有自定义函数,请查看此文档了解详细信息,您可以只使用await循环或在其上使用.then()

最新更新