javascript - 如何在完成具有 axios 调用的 for/forEach 循环执行后调用语句?

标签 javascript arrays loops 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 调用返回 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/

相关文章:

javascript - `if (idx < arr.length)` 相当于 `if (arr[idx])` 吗?

复制 C 中的字符串数组错误

linux - 创建 bash 脚本以 ssh 到不同的系统并运行命令

JavaScript 从特定元素/索引开始迭代 Map()

javascript - Ionic 3 - 从用户排序的数组中过滤列表

c++ - 检查哪个模块最接近

c# - 客户关系管理 2011 : Refresh associated Grid View

javascript - jQuery 修改动态生成的 HTML 表

javascript - Vue.js:观察数组长度

javascript - 如何获取相应按钮的值属性?