Javascript nodejs:mysql无法访问连接查询回调中的全局变量
下面是我的代码 我正在将数据对象从客户端javascript发送到此函数 数据打印其值 内插座 及 内部socket.on->connection.query(sql,[],函数(err,rows){data prints here}) 及 内部socket.on->connection.query(sql,[],函数(err,rows){data prints here})->connection.query(sql,[],函数(err,rows){data prints undefined})Javascript nodejs:mysql无法访问连接查询回调中的全局变量,javascript,mysql,node.js,sockets,Javascript,Mysql,Node.js,Sockets,下面是我的代码 我正在将数据对象从客户端javascript发送到此函数 数据打印其值 内插座 及 内部socket.on->connection.query(sql,[],函数(err,rows){data prints here}) 及 内部socket.on->connection.query(sql,[],函数(err,rows){data prints here})->connection.query(sql,[],函数(err,rows){data prints undefined}
您正在最深层创建新范围的
数据
:
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
- 开始使用
connection.query()
调用是异步的,对吧?@Pointy yesbro@Pointy它在first connection.query()中打印数据值,但关键是前两个查询几乎完全同时启动。connection.query()
函数调用会在查询实际完成之前立即返回。@非常感谢您提醒我使用非循环调用谢谢!我刚刚将数据更改为新数据
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.
...
}