You can solve this using the each function in the async package. Example:
async.each(elements, function(element, callback) {
// - Iterator function: This code will be executed for each element -
// If there's an error execute the callback with a parameter
if(error)
{
callback('there is an error');
return;
}
// If the process is ok, execute the callback without any parameter
callback();
}, function(err) {
// - Callback: this code will be executed when all iterator functions have finished or an error occurs
if(err)
console.log("show error");
else {
// Your code continues here...
}
});
This way your code is asynchronous (the iterator funcions are executed simultaneously) except the callback function that will be executed when all have finished.
The example with your code would be:
var elements = [1 .. n];
async.each(elements, function(element, callback) {
User.find( where { name: 'john'}, function(u) {
if(err)
{
callback(err);
return;
}
// Do things ...
callback();
});
}, function(err) {
if(err)
console.log("show error");
else {
// continue processing
}
});