Reputation: 744
This is my forEach loop. How to call a statement just after this loop is completed? I am unable to figure it out
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);
});
}
});
Upvotes: 0
Views: 82
Reputation: 117
Since axios calls return promises. What you can do is wait for all the promises to complete.
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.
Upvotes: 1
Reputation: 558
I recommend using p-iteration npm module, they have custom functions for every array-loop, check this doc for details, you can just await
loop or use .then()
on it
Upvotes: 0