繁体   English   中英

nodejs:mysql无法访问连接查询回调内的全局变量

[英]nodejs:mysql not able to access global variable inside connection query callback

下面是我的代码

我正在从客户端javascript发送数据对象到此函数,数据将打印其值

内部插座

在socket.on内-> connection.query(sql,[],function(err,rows){数据在这里打印})

内部socket.on-> connection.query(sql,[],function(err,rows){数据打印在这里})-> connection.query(sql,[],function(err,rows){数据打印未定义})

socket.on('sendmessage', function (data) {
    var data = JSON.parse(data);
    console.log(data);
    if (data.cuserid != '' && users_connected.hasOwnProperty(data.cuserid) && fs.existsSync(users_connected[data.cuserid]['sessionfile'])) {
        sql = "update hired set echat='Y' where eid=? and jobid=? and jid=? and status in ('given','finished')";
        connection.query(sql, [data.cuserid, data.jobid, data.userid], function (err, rows) {/*console.log(this.sql);*/ });
        sql = "insert into chat_messages(fromid,toid,jobid,message,received_date) select ?,?,?,?,NOW() from hired where echat='Y' and jchat='Y' and jobid=? and jid in(?,?) and eid in(?,?) and status in ('given','finished')";
        connection.query(sql, [data.cuserid, data.userid, data.jobid, data.message, data.jobid, data.cuserid, data.userid, data.cuserid, data.userid], function (err, rows) {
            console.log("dataretrieved : ", data); if (!err && users_connected[data.userid] != '') {
                socid = users_connected[data.userid]['socket'];
                sql = "select id as userid,username, userphoto from us_signup where id=?";
                connection.query(sql, [data.userid], function (err, rows) {
                    console.log(data);  //prints undefined                                   
                    if (!err) {
                        var data = {
                            'userphoto': rows[0].userphoto,
                            'username': rows[0].username,
                            'userid': rows[0].userid,
                            'cuserid': data.cuserid,
                            'message': data.message,
                            'jobid': data.jobid
                        }
                        io.to(socid).emit('message', JSON.stringify(data));
                    }
                })
            }
        });
    }

})

您正在创建最深层次的新范围data

if (!err) {
  var data = { ... }
  ...
}

此变量被提升到包含函数的顶部,因此代码等效于此:

var data;          // clobbers the existing `data` variable...
console.log(data); // ...so here it will log `undefined`...                           
if (!err) {
  data = { ... }   // ...because it receives a value here.
  ...
}

解决方案:

  • 不要在那里使用var
  • 开始使用let

暂无
暂无

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

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