Asynchronous calls inside loop [duplicate] Asynchronous calls inside loop [duplicate] express express

Asynchronous calls inside loop [duplicate]


very simple pattern is to use 'running tasks' counter:

var numRunningQueries = 0forEach(arrayelements) {  ++numRunningQueries;  asyncQueryFunction(function(qres) {    //work with query results.    --numRunningQueries;    if (numRunningQueries === 0) {       // finally, AFTER all callbacks did return:       res.render("myview");    }  });}

or, alternatively, use async helper library such as Async.js


If I understand correctly, asyncQueryFunction is always the same, as in you're applying the same update to each document.

I use a helper method to callback after saving (just swap for update) multiple mongoose documents (converted from CoffeeScript, so it may not be perfect):

function saveAll(docs, callback) {  // a count for completed operations, and save all errors  var count = 0    , errors = [];  if (docs.length === 0) {    return callback();  } else {    for (var i = 0; i < docs.length; i++) {      // instead of save, do an update, or asyncQueryFunction      docs[i].save(function(err) {        // increase the count in each individual callback        count++;        // save any errors        if (err != null) {          errors.push(err);        }        // once all the individual operations have completed,        // callback, including any errors        if (count === docs.length) {          return callback(errors);        }      });    }  }};saveAll(arrayElements, function(errors) {  // finally, AFTER all callbacks did return:  res.render("myview");}