【问题标题】:How to stop the execution of foreach until the end of the API call it has inside?如何停止执行 foreach 直到它内部的 API 调用结束?
【发布时间】: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]});
            }
        })

    });
}

谢谢!!

【问题讨论】:

标签: javascript angular typescript foreach angular5


【解决方案1】:

这是一个如何使用 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 之类的函数中实现您的请求,然后处理结果。

【讨论】:

    【解决方案2】:

    听起来您想将一个数组映射到一组承诺,然后等待所有并发工作完成后再做其他事情。

    我认为你会发现 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-06
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多