【发布时间】:2014-08-22 15:40:03
【问题描述】:
我知道节点的事件驱动/非阻塞的东西,我已经使用了大约 2 年... 最近我遇到了这个问题,即使强制关闭也无法解决...
我要求数据库提供一个简单的结果:'SELECT 1+1 as theResult'
(...) // previous code
var dbRows1 = {}; // empty object to hold rows
var dbRows2 = {}; // idem
var mysql = require( 'mysql' );
var db = mysql.createConnection( dbInfo ); // dbInfo has connction data
var test = function( a ) { dbRows2 = a };
db.connect(
function( err )
{
if (err) throw err.stack;
console.log( 'TID ->', db.threadId)
});
db.query (
'SELECT 1+1 AS XXX',
function( err, rows, fields )
{
console.log( 'rows ->', rows ); // works ok
dbRows1 = rows; // don't work because rows is still empty
test( rows ); // !!!should work but dbRows2 is empty at program end!!!
});
(...) // more code
console.log( dbRows2 );
最后一行为 dbRows2 ( { } ) 打印一个空对象...
为什么 console.log() 有效而我的 test() 函数无效的任何想法......
【问题讨论】:
-
你在哪里检查 dbRows2 '在程序结束'?因为查询是异步的,所以程序端必须等待查询完成,然后再检查 test 中分配的结果。
-
检查在程序结束...我将编辑示例以添加它...
标签: node.js asynchronous closures