title: Respond to request after all data is inserted to database
body: <p>I am trying to implement multiple data insertion on one call and trigger response only after all data is inserted. This is how I am currently doing it:</p>
  
  <pre><code>create: function(req, res) {
      var response = {};
      var num = req.body.num;
      var ret = 0;
  
      for (var i = 0; i &lt; num; i++) {
          var db = new user();
  
          db.enabled =  false;
          db.save(function(err){
              if(err) {
                // Handle error
              } else {
                ret++;
                // Do something
              }
          });
      }
  
      response = {"status" : 200, "message" : "It's working: " + ret};
      res.json(response);
  }
  </code></pre>
  
  <p>The problem with this approach is that all the callbacks for <code>save</code> will be triggered after <code>res.json(response)</code> which is wrong because sometimes I would also like to inform user how much data was saved. User will always receive the following response:</p>
  
  <pre><code>It's working: 0
  </code></pre>
  
  <p>Because <code>ret</code> variable is always 0. It's getting increased only after response is already triggered. What am I doing wrong?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Code after Will's suggestion:</p>
  
  <pre><code>var Q = require('q');
  
  create: function(req, res) {
      var response = {};
      var num = req.body.num;
      var ret = 0;
      var tasks = [];
  
      for (var i = 0; i &lt; num; i++) {
          var db = new user();
  
          db.enabled =  false;
  
          tasks.push(db.save());
      }
  
      Q.all(tasks).then(
          function(results) { 
            response = {"status" : 200, "message" : "It's working!"}; 
          }, 
          function(err) { 
            response = {"status" : 500, "message" : "Not working!" };
          );
  
      res.json(response);
  }
  </code></pre>