[英]How to stop the execution of foreach until the end of the API call it has inside?
I'm calling the service sending an array of ids as a parameter. 我正在调用发送ID数组作为参数的服务。 In the function I need to do a foreach of this ids and make an api call for each one to get the full info of this element and after that do something with that info.
在函数中,我需要对此id进行foreach并为每个API进行api调用以获取此元素的完整信息,然后再对该信息进行处理。
so how can I stop the execution of foreach until the end of the API call it has inside? 因此,如何停止执行foreach直到API调用结束为止?
The function: 功能:
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]});
}
})
});
}
Thanks!! 谢谢!!
Here is an Example how to use promise and map. 这是一个如何使用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]);
You can implement your request in a function like doSomthingToWaitFor
and handle the result afterwards. 您可以在
doSomthingToWaitFor
类的函数中实现您的请求,然后处理结果。
It sounds like you want to map an array to a set of promises, and then wait for all that concurrent work to finish before doing something else. 听起来您想将一个数组映射到一组Promise,然后等待所有并发工作完成之后再执行其他操作。
I think you will find map, promise and async/await very helpful here, eg 我认为您会在这里发现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.