处理与nodejsasynchronouscallback的循环
我是新的nodejs和mongoose。 我有一个从2009年到现在的数据库,并希望统计每个月的数据数量,并返回为json数组。 缓慢的asynchronouscallback会导致所有date为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);
在使用asynchronouscallback编写javascript时要小心。 当前的asynchronous完成后,您要做的是继续循环中的下一个项目。 您可以使用“asynchronous”模块: 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); });
- 有关电话号码的信息
- node.js将imagemagick的输出上传到AWS S3
- 用System.js导入Angular 2应用程序中的visionmedia debug以及如何logging消息?
- Javascript – 将以前的查询结果传递到下一个.then()
- 为什么这个基本的Node.jserror handling不起作用?
- 节点:试图使用`asynchronousfunction`抛出错误
- 我怎样才能服务的HTML,CSS和JS全部保持路由在一个module.export在不同的文件? 现在只有html服务
- 如何从节点中的文本文件中删除换行符空白?
- 我如何使用node.js和PHP来请求谷歌浏览器中的客户端js的大查询authentication