I'm running a semi-complex promise chain with a foreach loop in the middle. The issue I'm encountering is that the final .then() is being hit before the foreach loop completes resulting in a completely empty dailyTotals array.
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);
});
Is there a way to wait for that foreach loop to complete before resolving to the next .then()? The issue is directly on the foreach and the final console.log(dailyTotals);