【发布时间】:2023-04-03 13:47:01
【问题描述】:
我正在调用发送一组 id 作为参数的服务。在函数中,我需要对这些 id 做一个 foreach 并为每个 id 调用一个 api 来获取这个元素的完整信息,然后用这些信息做一些事情。
那么我怎样才能停止 foreach 的执行,直到它内部的 API 调用结束?
功能:
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.all()+.map() -
@Andreas 异步等待怎么样?
-
@Andreas 你能举一个这个解决方案作为答案的例子吗?
-
.forEach() 无法中断,请尝试使用.map()。
标签: javascript angular typescript foreach angular5