title: Javascript how to execute code after for loop completes
body: <p>I'm trying to work through this js/async scenario and i'm trying to know how the rest of the js world handles this. </p>
  
  <pre><code>function doStuff(callback) {
  
    cursor.each(function(err, blahblah) {
      ...doing stuff here takes some time
    });
  
    ... Execute this code ONLY after the `cursor.each` loop is finished
    callback();
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <p>Here's a more concrete example updated using most of the suggestions below which still doesn't work.</p>
  
  <pre><code>function doStuff(callback) {
  
    MongoClient.connect(constants.mongoUrl, function(err, db) {
  
      var collection = db.collection('cases2');
      var cursor = collection.find();
  
      var promises = [];  // array for storing promises
  
      cursor.each(function(err, item) {
  
        console.log('inside each'); // NEVER GETS LOGGED UNLESS I COMMENT OUT THIS LINE: return Q.all(promises).then(callback(null, items));
  
        var def = Q.defer();        // Create deferred object and store
        promises.push(def.promise); // Its promise in the array
  
        if(item == null) {
          return def.resolve();
        }
  
        def.resolve();  // resolve the promise
      });
  
      console.log('items'); // ALWAYS GETS CALLED
      console.log(items);
  
      // IF I COMMENT THIS LINE OUT COMPLETELY, 
      // THE LOG STATEMENT INSIDE CURSOR.EACH ACTUALLY GETS LOGGED
      return Q.all(promises).then(callback(null, items));
    });
  }
  </code></pre>