Como lidar com o loop in node.js?

estou a ter o seguinte código no nó.js.

var months =  ['jan','feb','march','april','may','june','july','august','sep','oct','nov','dec']
for(var i=0; j=months.length,i<j; i++){
  var start = scope.getCurrentUTS(new Date(2013, i, 1));
  var end = scope.getCurrentUTS(new Date(2013, i, 31));
  var query = {};
  query["stamps.currentVisit"] = {
        "$gte" : start.toString(),
        "$lt" : end.toString()
  };

     //connect to mongo and gets count coll.find(query).count(); working fine
  mongoDB.getCount(query,function(result) {
        console.log(result,i);  
  });
}

problema: Sendo o código está a correr async, a última linha de código não está a correr como esperado.

o resultado esperado é

10 0

11 1

12 2

.......

........

40 11

mas está a dar resultado como

indefinido 11

 2
Author: GEOCHET, 2013-09-18

1 answers

Provavelmente algumas das tuas perguntas não correspondem a nada. É por isso que retorna indefinido como resultado. Mas há outro problema. O i no callback async pode não ser o que você esperava. E será provavelmente igual a [[5]] meses.comprimento. Para manter o mesmo Eu você deve usar algo como:
var months =  ['jan','feb','march','april','may','june','july','august','sep','oct','nov','dec']
for(var i=0; j=months.length,i<j; i++){
    (function(i) {
        var start = scope.getCurrentUTS(new Date(2013, i, 1));
        var end = scope.getCurrentUTS(new Date(2013, i, 31));
        var query = {};
        query["stamps.currentVisit"] = {
            "$gte" : start.toString(),
            "$lt" : end.toString()
        };
        //connect to mongo and gets count coll.find(query).count(); working fine
        mongoDB.getCount(query,function(result) {
            console.log(result,i);  
        });
    })(i);
}

Também isto

for(var i=0; j=months.length,i<j; i++){

Pode ser apenas:

for(var i=0; i<months.length; i++){
 6
Author: Krasimir, 2013-09-18 06:21:02