如何从node.js中的函数外部访问局部variables

我在这里尝试的是访问函数外部的局部variables'htmlrows',但对node.js来说似乎并不那么容易。

var htmlrows; query.on('row', function(row) { console.log("%s |%s |%d", row.empid,row.name,row.age); htmlrows += "<tr><td>" + row.empid + "</td><td>" +row.name + "</td><td>" +row.age + "</td></tr>"; }); console.log("htmlrows outside function"); console.log(htmlrows); // console log prints 'undefined'. 

你能不能让我知道如何访问函数外的“htmlrows”?

非常感谢

你的问题是node.js是asynchronous的,所以console.log(htmlrows); 在查询function完成之前正在执行。

你需要做的是有一个单独的函数来侦听来自查询函数的callback。

您可以尝试使用node.js的asynchronous中间件,这将允许您串联asynchronous调用,以便按照某种顺序执行:

 var some_data = null; async.series([ function(callback) { //...do a thing function_1(callback); }, function(callback) { //...do another thing function_2(callback); } //...etc ]); function function_1(callback) { some_data = 'value'; console.log('function_1!'); return callback(); } function function_2(callback) { console.log('function_2: '+some_data); return callback(); } 

将导致:

 #:~ function_1! #:~ function_2: value