[英]How to stop the execution of foreach until the end of the API call it has inside?
我正在调用发送ID数组作为参数的服务。 在函数中,我需要对此id进行foreach并为每个API进行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和Map的示例。
let doSomthingToWaitFor = (ms) => { return new Promise(resolve => setTimeout(() => resolve('r-' + ms), ms)) } (async (ids) => { await Promise.all(ids.map(async id => { let res = await doSomthingToWaitFor(id); console.log("my res: %s from id: %s", res, id); })); console.log("Successfully waited"); })([1000, 2000, 3000, 4000]);
您可以在doSomthingToWaitFor
类的函数中实现您的请求,然后处理结果。
听起来您想将一个数组映射到一组Promise,然后等待所有并发工作完成之后再执行其他操作。
我认为您会在这里发现map,promise和async / await非常有帮助,例如
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.