首页 > 解决方案 > for of 循环甚至在 async/await 甚至在响应之前继续

问题描述

下面是我的代码片段,其中包含带有等待的异步调用。

let reccData = [] 

for (const uniformId of uniformCollectionIds) {
     let watchCreatives = await CreativeCollection.findById(uniformId);

     if(watchCreatives.isActive){
             let recommendations = await ReccService.fetchReccSeries(watchCreatives.reccNo);
             if(recommendations){
                  reccData.push({reccNo:recommendations.reccNo, watchList:recommendations.watchListId,...})
             } 
     }
}

Logistics.insertMany(reccData).then(() => {
    //My other business logic goes here
 });

ReccService.ts

public fetchReccSeries = async (reccNo:number) => {
    let getRecc = await Recc.findByNumber(reccNo)
    if(getRecc){
      return getRecc 
    }
};

上面代码的问题是,甚至在我从移动到下一次迭代中await ReccService.fetchReccSeries得到响应之前。for..of上面只是一个代码片段,我希望它以顺序方式执行的原因是,很多计数器/增量逻辑都基于此。

我试过的

一个.then({})承诺确认,但它的行为仍然相同。

前置await_for..of

for await (const uniformId of uniformCollectionIds) {

尝试Promise.All超出了我的范围

我所期待的:

直到每次迭代中的所有执行都没有完成,下一个 for 迭代不应该调用

标签: asynchronouspromiseasync-awaitfor-of-loop

解决方案


推荐阅读