首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >嵌套异步等待未按预期工作

嵌套异步等待未按预期工作
EN

Stack Overflow用户
提问于 2020-11-18 14:18:06
回答 3查看 398关注 0票数 1

我试图在我现有的代码中为一些数据添加一个表,为此,我已经设置了类似于exceljs文档中提到的所有内容。下面是我试图获取所需数据以获取表的条件的代码片段。当我在forEach中打印modRows时,它显示的是数据,但是当我在循环之外打印它时,它变得空白。有没有什么办法或者其他解决办法呢?是否可以在异步中使用异步?

代码语言:javascript
运行
复制
const generateCatReports = async (mode = 'monthly', months = 1, toDate = false) => {
  if (!['monthly', 'weekly'].includes(mode)) {
    throw new Error(InvalidParamsError);
  }
 const sortedTRIds = obtainSortedCentreIds(studiesTRMap, centreNameIDMap);
  const modRows = [];
  sortedTRIds.forEach(async (trId) => {
    console.log("trid",trId);
    const statsParams = {
      catId: trId,
      createdAt,
    };
    const statsPipeline = studiesStatsPipeline(statsParams, capitalize(mode));
    const statsInfo = await StudyModel.aggregate(statsPipeline).allowDiskUse(true).exec();
    Object.entries(statsInfo[0]).slice(1).forEach(([key, val]) => {
      modRows.push([key, val]);
    });
    console.log("inside sortedTr loop>>>>>" ,modRows);
  });
  console.log("outside sortedTr loop>>>>>>>>",modRows);

}

结果:

代码语言:javascript
运行
复制
trId 1cf1eb1324322bbebe
inside sortedTr loop>>>>>>>>>>
['TOTAL', 10]
['white', 5]
['black', 5]

trId 1cf1eb1324322bbebe
inside sortedTr loop>>>>>>>>>>
['TOTAL', 10]
['white', 5]
['black', 5]

trId 21e1eb21322bbebe
inside sortedTr loop>>>>>>>>>>
['TOTAL', 8]
['white', 6]
['black', 2]

outside sortedTr loop>>>>>>>>>>
[]
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-11-18 14:29:51

每当您看到像.forEach(async (trId) => {这样的异步回调时,出现问题的可能性都很高。

问题是,async函数实际上是promises,因此它们不会阻塞主线程。这意味着您的回调函数将在作业队列中排队,并将在将来执行。

它是这样简化的:

代码语言:javascript
运行
复制
let arr = []
setTimeout(() => {
   arr.push("hy")
})
console.log(arr)

arr将简单地为空,

但是,您可以使用for ... of循环

代码语言:javascript
运行
复制
const generateCatReports = async (
  mode = "monthly",
  months = 1,
  toDate = false
) => {
  if (!["monthly", "weekly"].includes(mode)) {
    throw new Error(InvalidParamsError);
  }
  const sortedTRIds = obtainSortedCentreIds(studiesTRMap, centreNameIDMap);
  const modRows = [];
  for (const trId of sortedTRIds) {
    const statsParams = {
      catId: trId,
      createdAt
    };
    const statsPipeline = studiesStatsPipeline(statsParams, capitalize(mode));
    const statsInfo = await StudyModel.aggregate(statsPipeline)
      .allowDiskUse(true)
      .exec();
    Object.entries(statsInfo[0])
      .slice(1)
      .forEach(([key, val]) => {
        modRows.push([key, val]);
      });
    console.log("inside sortedTr loop>>>>>", modRows);
  }
  console.log("outside sortedTr loop>>>>>>>>", modRows);
};

在这里,您没有要排队的回调。

更好的解决方案是使用Promise.all()

代码语言:javascript
运行
复制
const generateCatReports = async (
  mode = "monthly",
  months = 1,
  toDate = false
) => {
  if (!["monthly", "weekly"].includes(mode)) {
    throw new Error(InvalidParamsError);
  }
  const sortedTRIds = obtainSortedCentreIds(studiesTRMap, centreNameIDMap);
  const modRows = await Promise.all(
    sortedTRIds.flatMap(async (trId) => {
      const statsParams = {
        catId: trId,
        createdAt
      };
      const statsPipeline = studiesStatsPipeline(statsParams, capitalize(mode));
      const statsInfo = await StudyModel.aggregate(statsPipeline)
        .allowDiskUse(true)
        .exec();
      return Object.entries(statsInfo[0]).slice(1);
    })
  );

  console.log(modRows);
};
票数 2
EN

Stack Overflow用户

发布于 2020-11-18 14:22:28

不能在forEach周期中使用async/await。你可以在一个简单的for循环或一段时间内使用它,做...

例如:

代码语言:javascript
运行
复制
export async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  }
}
票数 2
EN

Stack Overflow用户

发布于 2020-11-18 14:37:01

这就是为什么你不应该在forEach循环中使用异步/等待,

forEach循环接受回调,即使您将异步函数作为回调传递也不会等待。异步回调将等待它内部的任何承诺,但forEach循环将继续为数组中的所有元素执行回调函数。

而不是使用for...in循环,正如预期的那样,for...in循环内部的等待将停止循环执行,并仅在您完成对promise的等待时才继续迭代。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64888029

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档