I'm having trouble getting the flow of a number of asynchronous operations to flow right. As my code below stands now, the outside readFile prints to the console first, then the names and years print next, and then finally the in readFile, when I'd like the entire readFile/forEach processing to happen before.
const fs = require('fs')
const names = {}
const years = {}
fs.readdir('./namesData', (err, files) => {
files.forEach(file => {
var year = file.substr(3, 4)
var yearObj = {}
fs.readFile(`./namesData/${file}`, 'utf8', (err, data) => {
console.log('in readFile')
if (err) throw new Error(err)
var arr = data.split('\n')
arr.forEach(record => {
var recordArray = record.trim().split(',')
var name = recordArray[0]
var gender = recordArray[1]
var score = recordArray[2]
// populate 'names' object
var nameObj = {year: year, gender: gender, score: score}
if (names.hasOwnProperty(name)) {
names[name].push(nameObj)
} else {
names[name] = [nameObj]
}
// populate 'years' object & add to yearObj and then years object
var yearNameObj = {gender: gender, score: score}
if (yearObj.hasOwnProperty(name)) {
yearObj[name].push(yearNameObj)
} else {
yearObj[name] = [yearNameObj]
}
})
})
console.log('outside readFile')
years[year] = yearObj
})
console.log(names)
console.log(years)
})
yearsandnameswill look like?