简体   繁体   中英

How to handle for loop in node.js?

I am having following code in node.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);  
  });
}

Problem : Being code is running async, last line of code is not running as expected.

output expected is

10 0

11 1

12 2

.......

........

40 11

but it is giving output as

undefined 11

Probably some of your queries doesn't match anything. That's why it returns undefined as result. But there is another problem. The i in the async callback may be not what you expected. And will be probably equal to months.length . To keep the same i you should use something like:

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);
}

Also this

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

Could be just:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM