Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are a few problems with your code besides just the callback structure.</p> <pre><code>var contacts = req.body; (function(res, contacts) { ... })(); // function </code></pre> <p>^ you are redefining <code>contacts</code> and <code>res</code> in the parameter list, but not passing in any arguments, so inside your function <code>res</code> and <code>contacts</code> will be <code>undefined</code>.</p> <p>Also, not sure where your <code>self</code> variable is coming from, but maybe you defined that elsewhere.</p> <p>As to the callback structure, you're looking for something like this (assuming contacts is an Array):</p> <pre><code>exports.contacts_create = function(req, res) { var contacts = req.body; var iterator = function (i) { if (i &gt;= contacts.length) { res.json('finished'); // or call self.response() or whatever return; } contact = contacts[i]; var newContact = new Contact(contact); newContact.user = req.user.id newContact.save(function(err) { if (err) console.log(err); //if this is really a failure, you should call response here and return iterator(i + 1); //re-call this function with the next index }); }; iterator(0); //start the async "for" loop }; </code></pre> <p>However, you may want to consider performing your database saves in parallel. Something like this:</p> <pre><code>var savesPending = contacts.length; var saveCallback = function (i, err) { if (err) console.log('Saving contact ' + i + ' failed.'); if (--savesPending === 0) res.json('finished'); }; for (var i in contacts) { ... newContact.save(saveCallback.bind(null, i)); } </code></pre> <p>This way you don't have to wait for each save to complete before starting the next round-trip to the database.</p> <p>If you're unfamiliar with why I used <code>saveCallback.bind(null, i)</code>, it's basically so the callback can know which contact failed in the event of an error. See <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind" rel="nofollow">Function.prototype.bind</a> if you need a reference.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload