Javascript 如何停止foreach的执行,直到其内部的API调用结束?
我正在调用服务,将ID数组作为参数发送。在函数中,我需要对每个ID进行一次foreach操作,并对每个ID进行一次api调用,以获取该元素的完整信息,然后对该信息进行处理 那么,在foreach内部的API调用结束之前,如何停止foreach的执行呢 职能:Javascript 如何停止foreach的执行,直到其内部的API调用结束?,javascript,angular,typescript,foreach,angular5,Javascript,Angular,Typescript,Foreach,Angular5,我正在调用服务,将ID数组作为参数发送。在函数中,我需要对每个ID进行一次foreach操作,并对每个ID进行一次api调用,以获取该元素的完整信息,然后对该信息进行处理 那么,在foreach内部的API调用结束之前,如何停止foreach的执行呢 职能: addCandidate(ids: any, candidate: string) { ids.forEach(elem => { this.getSearch(elem).subscribe(res =&
addCandidate(ids: any, candidate: string) {
ids.forEach(elem => {
this.getSearch(elem).subscribe(res => {
let currentCandidates = res.candidates;
if(currentCandidates) {
if(!currentCandidates.includes(candidate)){
currentCandidates.push(candidate);
this.itemDoc.update({candidates: currentCandidates});
}
}else{
this.itemDoc.update({candidates: [candidate]});
}
})
});
}
谢谢 下面是一个如何使用promise和map的示例
让doSomthingToWaitFor=(ms)=>{
返回新承诺(resolve=>setTimeout(()=>resolve('r-'+ms),ms))
}
(异步(ids)=>{
等待Promise.all(ids.map)(异步id=>{
let res=等待doSomthingToWaitFor(id);
log(“我的res:%s来自id:%s”,res,id);
}));
log(“已成功等待”);
})([1000, 2000, 3000, 4000]);代码>听起来您想将一个数组映射到一组承诺,然后等待所有并发工作完成,然后再执行其他操作
我想您会发现map、promise和async/wait在这里非常有用
const ids = [1, 2];
const work = await Promise.all(
ids.map(ajaxCall)
);
// 'await' means that this won't be called until the Promise.all is finished
printToScreen(work);
Promise.all()
+.map()
@Andreas异步等待怎么样?@Andreas您能给出一个实现此解决方案的示例作为答案吗?无法中断,请改为尝试。