如何处理 node.js 中的 for 循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18864964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle for loop in node.js?
提问by karthick
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
回答by Krasimir
Probably some of your queries doesn't match anything. That's why it returns undefinedas result. But there is another problem. The iin the async callback may be not what you expected. And will be probably equal to months.length. To keep the same iyou should use something like:
可能您的某些查询与任何内容都不匹配。这就是为什么它返回undefined作为结果。但还有一个问题。异步回调中的i可能不是您所期望的。并且可能等于months.length。为了保持不变i你应该使用类似的东西:
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++){

