[英]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.