My basic question is similar to this previous post, except that I also have two loops going within my callback (to grab data from two arrays and eventually return an array of json objects in the browser). Here is my code:
router.get('/users', function(req, res) {
userColl.find().toArray(function (err, items) {
if (err) {console.log(err + ': err');} else {
var userlist = [];
items.forEach(function (dj) {
showColl.find({hostId: dj._id}).toArray(function (err, shows) {
if (err) {console.log('showFind error: ' + err);} else {
shows.forEach( function (show) {
userlist.push(
{
_id: dj._id,
access: dj.access,
firstName: dj.firstName,
lastName: dj.lastName,
gradYear: dj.gradYear,
shows: show.showTitle,
show_id: show._id
}
);
// =============== SPOT #2 =============
}); // end shows loop
}
}); // end showColl.find
}); // end items.forEach
console.log(JSON.stringify(userlist) + ' ul');
res.render('admin/users/manageUsers', {
"userlist" : userlist,
title: 'view users'
});
} // end if/else
}); // end userColl.find callback
});
I assumed that what I have would work, and it returns no errors, but since it's asynchronous the userlist
variable is blank when the page is rendered. If I put the render command in the show loop (SPOT #2) it renders the page after just the first loop, so I have one item instead of the dozens that I'm expecting. If I put the render call anywhere in between its current location and SPOT #2 I get an error for calling multiple responses. Is there any way to delay the render command until the callback has been complete without placing it in the callback? Any advice much appreciated.