I am exploring using q instead of async - then I ran across the issue addressed here:
Mongoose JS promises? Or how to manage batch save
What would this answer have been if I was using q?
See my comment for an issue I ran into using ForbesLindesay's solution. Here is what I ended up with (just added ninvoke to return a promise):
var tasks = [];
for (var i=0; i < docs.length; i++) {
tasks.push(Q.ninvoke(docs[i], "save"));
}
Q.all(tasks)
.then(functions, function(results) {
console.log(results);
}, function (err) {
console.log(err);
});
See post by @rquinn, this code might not actually work if docs[i].save() is not returning a promise.
var tasks = [];
for (var i=0; i < docs.length; i++) {
tasks.push(docs[i].save());
}
Q.all(tasks)
.then(functions, function(results) {
console.log(results);
}, function (err) {
console.log(err);
});
We start all the operations one at a time in the loop, but we don't wait for any of them to complete, so they run in parallel. We add a promise (that acts like a placeholder for the result) to an array. We then wait for all the promises in the array of promises to complete.