繁体   English   中英

使用Node.js异步回调处理循环

[英]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时要小心。 您要做的是在当前异步操作完成后继续循环中的下一个项目。 您可以使用“异步”模块: 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);
});

暂无
暂无

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

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