title: Node async callback: How to return an object within a loop in a callback?
body: <p>My basic question is similar to this <a href="https://stackoverflow.com/questions/8731459/node-js-how-to-properly-return-an-object-from-within-a-callback">previous post</a>, 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:</p>
  
  <pre><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   
  });
  </code></pre>
  
  <p>I assumed that what I have would work, and it returns no errors, but since it's asynchronous the <code>userlist</code> 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 <em>without</em> placing it in the callback? Any advice much appreciated.</p>