简体   繁体   English

如何处理node.js中的for循环?

[英]How to handle for loop in node.js?

I am having following code in node.js. 我在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 10 0

11 1 11 1

12 2 12 2

....... .......

........ ........

40 11 40 11

but it is giving output as 但它给输出为

undefined 11 未定义11

Probably some of your queries doesn't match anything. 您的某些查询可能不匹配任何内容。 That's why it returns undefined as result. 这就是为什么它返回undefined作为结果的原因。 But there is another problem. 但是还有另一个问题。 The i in the async callback may be not what you expected. 异步回调中的i可能不是您期望的。 And will be probably equal to months.length . 并且可能等于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++){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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