È possibile risolvere questo utilizzando la funzione di ogni nel async package. Esempio:
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...
}
});
questo modo il codice è asincrona (i funcions iteratori vengono eseguiti simultaneamente) eccetto la funzione di richiamata che viene eseguito quando tutti hanno finito.
L'esempio con il codice sarebbe:
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
}
});
Che cosa esattamente cosa si vuole realizzare con il ciclo? – amenadiel
Prova ad usare una promessa. Dai un'occhiata a: http://howtonode.org/promises – Sid