使用nodejs异步回调处理循环
Handling loop with nodejs asynchronous callback
我是nodejs和mongoose的新手。我有一个从2009年到现在的数据库,我想统计每个月的数据数量,并以json数组的形式返回。慢速异步回调导致所有日期截至2014年8月1日
实现这一点的正确方法是什么?
var dbURL = 'mongodb://localhost/database';
var db = require('mongoose').connect(dbURL);
var c_db = require('./models/models.js').c_db;
var start_date = new Date(2009,0,1);
end_date = new Date(2014,8,1),
next_date = new Date();
var test_json=[];
var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth());
var next_date = start_date;
for(var i=0;i<total_months;i++){
var firstDay = new Date(next_date.getFullYear(), next_date.getMonth(), 1);
var lastDay = new Date(next_date.getFullYear(), next_date.getMonth() + 1, 0);
next_date.setDate(lastDay.getDate()+1);
c_db.count({'shipdate':{'$gte':new Date(firstDay),'$lte':new Date(lastDay)}},function(err,query){
var item = {
"Date": firstDay,
"Count": query
}
test_json.push(item);
});
}
setTimeout(function(){
console.log(test_json);
},5000);
使用异步回调编写javascript时要小心。您想要做的是在当前异步完成后继续循环中的下一项。您可以使用"async"模块:https://github.com/caolan/async
var async = require("async");
var dbURL = 'mongodb://localhost/database';
var db = require('mongoose').connect(dbURL);
var c_db = require('./models/models.js').c_db;
var start_date = new Date(2009,0,1);
end_date = new Date(2014,8,1),
next_date = new Date();
var test_json=[];
var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth());
var next_date = start_date;
async.timesSeries(total_months, function(n, next) {
var firstDay = new Date(next_date.getFullYear(), next_date.getMonth(), 1);
var lastDay = new Date(next_date.getFullYear(), next_date.getMonth() + 1, 0);
next_date.setDate(lastDay.getDate()+1);
c_db.count({'shipdate':{'$gte':new Date(firstDay),'$lte':new Date(lastDay)}},function(err,query){
var item = {
"Date": firstDay,
"Count": query
}
test_json.push(item);
next();
});
}, function(e) {
console.log(test_json);
});
相关文章:
- 如何使用jquery处理php循环通过元素
- Javascript在for循环中等待处理请求
- 在循环中附加事件处理程序时出现浏览器性能问题
- 如何处理javascript中的循环引用,类似于Excel提供迭代限制的方式
- Emberjs#每个循环不处理数组数据
- jQuery:如何在没有for循环的情况下将事件处理程序应用于$('#text'+'任意整数
- 在嵌套循环中处理 AJAX (Angularjs)
- RxJS:在循环中处理错误.js自定义驱动程序
- 在处理元素单击事件期间,在循环内部调用window.open()
- 将事件处理程序分配给for循环中的每个按钮
- 如何在 JavaScript 和浏览器中处理循环引用
- 处理循环变量的重复声明警告
- 添加HTML按钮以处理循环数组中的元素上的增量
- 使用nodejs异步回调处理循环
- 处理循环依赖
- 在单独的文件中考虑模型:如何处理循环/循环依赖关系
- 处理循环数组请求的错误
- 如何在AngularJS中处理循环中的if语句
- 以角度同步处理循环
- 如何在这样的javascript代码中处理循环复杂性