3

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

1 Answer 1

8

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++){
Sign up to request clarification or add additional context in comments.

1 Comment

use should be used let in place of var in for loop for better approach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.