Javascript 在完成for/forEach循环执行并调用axios后,如何调用语句?

Javascript 在完成for/forEach循环执行并调用axios后,如何调用语句?,javascript,arrays,loops,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)

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

我建议使用npm模块,它们对每个数组循环都有自定义函数,请检查此项了解详细信息,您可以等待
循环或在其上使用
.then()
,因为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.
let jobs:Promise[]=[];
array.forEach(项=>{
log(“循环已启动”);
让id=[item.id];
let type=item.type;
如果(子类型==“a”){
const job=api.method(类型,id)
。然后(响应=>{
console.log(“response.data:>>”,response.data);
})
.最后(()=>{
log(“最终项:>>”,项);
});
推(作业);
}else if(子类型==“b”){
const job=api.method(类型,id)
。然后(响应=>{
console.log(“response.data:>>”,response.data);
})
.最后(()=>{
log(“最终项:>>”,项);
});
jobs.push(作业)
}
});
等待承诺。所有(工作);
//这里的代码将在所有承诺都得到解决后开始执行。

您声明新承诺的那一行似乎是用打字脚本写的。它给出了一个错误,“类型”只能在.ts文件中使用。由于我在理解承诺的概念方面有点新手,您能帮助我用javascript声明它吗@dilanka
let jobs=[]