I've been staring at my screen for too long and can't seem to figure this out... Basically i do 3 query's using mongoose, each one building on the result of the other one. For some reason the parent call finished before the child can complete it's tasks. This is my code, why are the parents not waiting to continue untill the child has finished the work? How can i make it so the code runs as i want it to :-)
I have been told to use promises, but it looks so complicated to use and i assume the use of callbacks would be enough to handle async calls or am i wrong?
var ctr = 0; // counter 1
var ct2 = 0; // counter 2
//Array to be used for the header of the csv file
var mainArr = [["Personeelsnummer", "Chauffeur", "Week 1", "Week 2", "Week 3", "Week 4"]];
// Find all users in the database
User.find({}).exec(function (err, users){
// forEach user, push some basic data into tempArr
// and lookup planned weeks (geplandeWeken) using another mongoose function
users.forEach(function(user){
var tempArr = [];
tempArr.push(user.personeelsnummer);
tempArr.push(user.fullName);
user.geplandeWeken.forEach(function(week1){
Week.findById(week1, function(err, foundWeek){
tempArr.push(foundWeek.week);
ctr++;
if(ctr === user.geplandeWeken.length){
mainArr.push(tempArr);
console.log(mainArr);
}
});
});
ct2++;
});
if(ct2 === users.length){
console.log(ct2);
csv.write(mainArr, {headers:true}).pipe(res);
}
});
So long story short : users.forEach finishes before user.geplandeWeken.forEach is able to do it's job. The csv file is send to the user before any data could be collected and stored into the csv file.