【发布时间】:2020-04-04 21:00:29
【问题描述】:
我正在运行一个半复杂的承诺链,中间有一个 foreach 循环。我遇到的问题是最终的.then() 在foreach 循环完成之前被命中,导致dailyTotals 数组完全为空。
fs.readdir(csvPath)
.then(files => {
// Define storage array
var csvFiles = [];
// Loop through and remove non-csv
files.forEach(file => {
if (file !== "README.md" && file !== ".gitignore") {
csvFiles.push(file);
}
});
return csvFiles;
})
.then(files => {
var dailyTotals = [];
files.forEach(filename => {
const loadedFile = fs.createReadStream(csvPath + filename);
var totalCases = 0;
var totalDeaths = 0;
var totalRecovered = 0;
papa.parse(loadedFile, {
header: true,
worker: true,
step: r => {
totalCases += parseIntegerValue(r.data.Confirmed);
totalDeaths += parseIntegerValue(r.data.Deaths);
totalRecovered += parseIntegerValue(r.data.Recovered);
},
complete: () => {
var dailyTotal = {
date: filename.replace(".csv", ""),
parsed: {
confirmed: totalCases,
deaths: totalDeaths,
recovered: totalRecovered
}
};
dailyTotals.push(dailyTotal);
}
});
});
return dailyTotals;
})
.then(dailyTotals => {
console.log(dailyTotals);
});
有没有办法在解析到下一个.then() 之前等待该foreach 循环完成?问题直接在foreach和最终console.log(dailyTotals);
【问题讨论】:
-
查看
Promise.all -
没有。你不会让
.forEach等待。但是,您还可以通过稍微不同的方法来实现这一目标: 1. 使用传统的 for 循环。 -
或
Promise.allSettled
标签: javascript asynchronous foreach promise