MySQL回调和范围

时间:2013-12-23 04:07:14

标签: mysql json node.js api express

我在使用node-mysql使用express构建网络API时遇到问题。我有以下文件,。/ lib / weblers / list.js,已加载,一切都很好(使用require('./lib/handlers/list.js')(app)):

var error= function(res){
  res.json([]);
}

var send_lists = function(res,lists){
    res.json(lists);
}

var add_tasks_to_lists = function(res,lists){
    for (var i = 0, list; i < lists.length, list=lists[i]; i++) {
        var connect=require('../../mysql.js').connection();
            connect.connect();
            connect.query("SELECT * FROM `www`.`teamli_tasks` WHERE `list_id`="+connect.escape(list['id'])+";",function(_err,_rows){
              if(!_err && _rows && _rows.length){
                var tasks=[];
                for(var j=0, _row; j < _rows.length, _row=_rows[j], _row!=null; j++){
                  var task={};
                  task['id']=_row.id;
                  task['text']=_row.text;
                  task['completed']=_row.completion?true:false;
                  tasks.push(task);
                }
                list['tasks']=tasks;
              }
            });
    }
    send_lists(res,lists);
}

module.exports = function(app){
  app.post('/api/list',function(req,res){
    console.log(req.session);
    if(req.hasOwnProperty("body") && req.body && req.hasOwnProperty("session") && req.session && req.session.hasOwnProperty("user") && req.session.user && req.session.user.hasOwnProperty("id") && req.session.user.id){
      var connection=require('../../mysql.js').connection();
      connection.connect();
      connection.query("SELECT * FROM `www`.`teamli_lists` WHERE `owner_id`="+connection.escape(req.session.user.id)+";",function(err, rows){
        if(!err && rows && rows.length){
          var lists=[];
          for (var i = 0, row; i < rows.length, row=rows[i]; i++) {
            console.log("Getting list with ID: "+row.id);
            var list={};
            list['participants']=req.session.user.username;
            list['timeenforcer']=null;
            list['id']=row.id;
            list['date']=1382659200;
            list['duedate']=null;
            list['title']=row.name;
            list['color']=row.color;
            console.log(list);
            lists.push(list);
          }
        add_tasks_to_lists(res,lists);
        }else error(res);
      });
    }else error(res);
  });
}

但是,当命中此API端点(/ api / list)时,我收到此错误:

TypeError: Cannot set property 'tasks' of undefined
    at Query._callback (/var/www/main/www/lib/handlers/api/list.js:24:27)

require('../../mysql.js').connection()生成一个新的node-mysql Connection对象,使用mysql.js中提供的凭据进行设置。 teamli_lists和teamli_tasks都包含相关数据,由id / list_id连接。

我对Node有点新,特别是像这样的异步,所以任何帮助都表示赞赏。如果您需要更多信息,请与我们联系。谢谢!

2 个答案:

答案 0 :(得分:0)

错误表明属性'tasks'正在未定义的变量上使用。您尝试设置'tasks'属性的位置在此处:

list['tasks']=tasks;

但是在for循环中声明时,列表永远不会被初始化。试试list = {};(空对象)

答案 1 :(得分:0)

我设法让这个工作正常 - 我仍然必须释放连接,我知道,并整理整理代码,但现在这样做:

var lists=[];
var lists_count;

var error= function(res){
  res.json([]);
}

var send_lists = function(res,lists){
    res.json(lists);
}

var add_list = function(res,list){
    lists.push(list);
    if(lists.length==lists_count) send_lists(res,lists);
}

var add_tasks_to_list = function(res,list,callback){
    console.log("Adding task to list: "+list);
        var connect=require('../../mysql.js').connection();
            connect.connect();
            connect.query("SELECT * FROM `www`.`teamli_tasks` WHERE `list_id`="+connect.escape(list['id'])+";",function(_err,_rows){
              if(!_err && _rows && _rows.length){
                var tasks=[];
                for(var j=0, _row; j < _rows.length, _row=_rows[j], _row!=null; j++){
                  var task={};
                  task['id']=_row.id;
                  task['text']=_row.text;
                  task['completed']=_row.completion?true:false;
                  tasks.push(task);
                }
                list['tasks']=tasks;
              }
                callback(res,list);
            });
}

module.exports = function(app){
  app.post('/api/list',function(req,res){
    console.log(req.session);
    if(req.hasOwnProperty("body") && req.body && req.hasOwnProperty("session") && req.session && req.session.hasOwnProperty("user") && req.session.user && req.session.user.hasOwnProperty("id") && req.session.user.id){
      var connection=require('../../mysql.js').connection();
      connection.connect();
      connection.query("SELECT * FROM `www`.`teamli_lists` WHERE `owner_id`="+connection.escape(req.session.user.id)+";",function(err, rows){
        if(!err && rows && rows.length){
            lists_count=rows.length;
          for (var i = 0, row; i < rows.length, row=rows[i]; i++) {
            console.log("Getting list with ID: "+row.id);
            var list={};
            list['participants']=req.session.user.username;
            list['timeenforcer']=null;
            list['id']=row.id;
            list['date']=1382659200;
            list['duedate']=null;
            list['title']=row.name;
            list['color']=row.color;
            add_tasks_to_list(res,list,add_list);
          }
        }else error(res);
      });
    }else error(res);
  });
}