BeaST 30
BeaST 30

Reputation: 744

How to call a statement after complete for/forEach loop execution having axios calls?

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

Answers (2)

Dilanka Asiri
Dilanka Asiri

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

Vahe Yavrumian
Vahe Yavrumian

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

Related Questions