我试图在我现有的代码中为一些数据添加一个表,为此,我已经设置了类似于exceljs文档中提到的所有内容。下面是我试图获取所需数据以获取表的条件的代码片段。当我在forEach中打印modRows时,它显示的是数据,但是当我在循环之外打印它时,它变得空白。有没有什么办法或者其他解决办法呢?是否可以在异步中使用异步?
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);
}结果:
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>>>>>>>>>>
[]发布于 2020-11-18 14:22:28
不能在forEach周期中使用async/await。你可以在一个简单的for循环或一段时间内使用它,做...
例如:
export async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}https://stackoverflow.com/questions/64888029
复制相似问题