【问题标题】:How to call a statement after complete for/forEach loop execution having axios calls?完成具有axios调用的for/forEach循环执行后如何调用语句?
【发布时间】:2020-05-03 18:14:03
【问题描述】:

这是我的 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);
                    });
            }
        });

【问题讨论】:

    标签: javascript arrays loops foreach


    【解决方案1】:

    由于 axios 调用返回承诺。你可以做的是等待所有的承诺完成。

    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.
    

    【讨论】:

    • 你声明新承诺的那一行似乎是用打字稿写的。它给出了一个错误“类型”只能在 .ts 文件中使用。由于我在理解 Promise 的概念方面有点新手,你能帮我在 javascript 中声明它吗? @dilanka
    • let jobs = [];
    【解决方案2】:

    我推荐使用p-iteration npm 模块,它们对每个数组循环都有自定义函数,请查看doc 了解详细信息,您可以只使用await 循环或在其上使用.then()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-01
      • 2012-12-04
      • 2021-01-02
      • 2017-07-27
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2013-06-02
      相关资源
      最近更新 更多