NODEJS node-mysql无法在嵌套查询中传递查询结果

时间:2014-07-05 12:11:58

标签: mysql json node.js angularjs callback

我正在使用node,angular和mysql,节点路由将返回一个将由angular处理的json,通过首先使用node-mysql模块查询mysql数据库返回json, 在下面的代码中,我无法设置CreatedID的值,但是在终端中正确记录了该值。我在第一个查询中遇到了同样的问题,但后来在下面的代码中对它进行了排序,现在无法访问嵌套的查询结果。

           var mysql =  require('node-mysql/node_modules/mysql');

 var connection =  mysql.createConnection({
    host : 'localhost',
    user : "root",
    password: "",
    database:'designtaskmanager'
  });
 connection.connect();
var allDbCalls = function() {
   var sendData = {};
   var rowData = {};
   var temp={};
   var _this = this;
   this.sendTask = function(callback) {
     module.exports.taskData =  rowData;
     callback['success']();
  };



  this.getTask = function(callback) {
    var strQuery = "select * from  task"; 
    connection.query( strQuery, function(err, rows){
      if(err) 
      {
        callback['failure']();
        throw err;
      }
      else
      {
        //rowData = rows;
        var tasks=[];

        for (var i in rows) 
        {
            var Title = rows[i].task_title;
            var TaskDescription=rows[i].task_description;
            var TaskCategory=rows[i].task_category;
            var TaskID=rows[i].task_id;
            var TaskStatus=rows[i].task_status;
            var TaskStatusMessage
            var CreatedBy;
            var TaskCreationDate=rows[i].task_creation_date;
            var _MS_PER_DAY = 1000 * 60 * 60 * 24;



            var currentdate = new Date(); 

            var ddd=dateDiffInDays(TaskCreationDate,currentdate);

            function dateDiffInDays(a, b) {
              // Discard the time and time-zone information.
              var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
              var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

              return Math.floor((utc2 - utc1) / _MS_PER_DAY);
            }

            if(TaskStatus==0)
            {
              TaskStatus="label-info";
              TaskStatusMessage="Ongoing since";

            }
            else if(TaskStatus==1)
            {
              TaskStatus="label-default";
              TaskStatusMessage="Paused since"

            } 
            else if(TaskStatus==2)
            {
              TaskStatus="label-success";
              TaskStatusMessage="Completed in"

            }

            //USER DETAILS QUERY
            var crid=rows[i].task_created_by;
            var creatorQuery = "select user_email from  users where user_id like ?";

            connection.query( creatorQuery,[crid], function(err, createdbyrows){
              if(err) 
              {
                callback['failure']();
                throw err;
              }
              else
              {
                for(var j=0; j< createdbyrows.length;j++)
                {
                  CreatedBy=createdbyrows[0].user_email;
                  console.log(j);


                }

                  console.log(CreatedBy);

              }
          });


            var taskItem={"TaskID":TaskID,"TaskTitle":Title,"TaskDescription":TaskDescription,"TaskCategory":TaskCategory,"CreatedBy":CreatedBy,"TaskStatus":TaskStatus,"TaskStatusMessage":TaskStatusMessage,"DifferenceInDays":ddd};

          tasks.push(taskItem);

        }

          rowData=tasks;
           _this.sendTask(callback);   
      }
    });
  }

}
module.exports = function () {
  var instance = new allDbCalls();
  return instance;
};

1 个答案:

答案 0 :(得分:0)

您在控制台上看到它而不是在回调中看到它的原因是由于对异步编程的误解。当你:

for(var i in rows) {}

您实际上是在同时排队所有这些查询,然后,在您尝试将rowData设置为空数组后立即:

rowData=tasks; // remember, none of the queries have finished yet
_this.sendTask(callback);  

因此,当任务仍为空数组时,您几乎会调用回调。请记住,在所有嵌套查询完成之前,您无法调用最终回调函数!

要完成此操作,您可能需要查看异步库:https://github.com/caolan/async#eachSeries

这将帮助您实现您真正想要的目标。

var async = require("async");
async.eachSeries(rows, function(row, cb) {
   // Do each query here
   // then call cb() when done, which tells the async library 
   // to "go to the next item in the array"
}, function(err) {
   // This will get called when all of the single queries are finished
   // Check err, then call your callback
   _this.sendTask(callback);   
});