Node.jsvariables作用域

我有一个http服务器设置,基本上需要查找数据库中的东西。

这里是代码片段:

var sys = require('sys'); var Client = require('mysql').Client; var client = new Client(); client.host = '_'; client.user = '_'; client.password = '_'; client.database = '_'; var http = require('http'); http.createServer(function(req, res) { req.on('end', function() { client.connect(function(error, results) { if (error) { console.log('Connection Error:'); return; } ClientConnectionReady(client); }); ClientConnectionReady = function(client) { var final = ''; client.query('select * from table', function selectCb(error, result, fields) { if (error) { console.log('ERROR'); client.end(); return; } final += "{" + JSON.stringify(result); }); client.query("SELECT COUNT(*) from table", function selectCb(error, result, fields) { if (error) { console.log('ERROR'); client.end(); return; } final += "," + JSON.stringify(result) + "}"; }); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write(final); res.end(); client.end(); }; }); }).listen(8007, "127.0.0.1"); 

如果我在分配的地方打印variables“final”的值,我会看到有效的值,但是当我执行'res.write(final)'时,final仍然是空的。

我如何做这个工作,为什么这个失败? 感谢您的帮助,我是node.js的新手

Node.js环境是asynchronous的 。 那些修改“final”的语句是只在数据库操作完成时执行的内部callback。 在数据库操作启动之后,您在其中编写结果的代码将立即在这些callback运行之前执行。

你已经几乎偶然发现了这个问题的答案:在操作完成之前,你不能直接写出结果,你知道在callback中就是这种情况。 如果你必须等待完成(看起来像你),那么你可以做一些事情,如在外部范围内保留一个计数器。 每个callback可以递增计数器,并且只有当计数器指示两个callback完成时才调用相同的结果写入器function。 (我有这样的想法,即Node运行时有更奇妙的做法,但我并不熟悉它,在这种简单的情况下,保持类似于计数器的事情是很容易的。

另外,还有一个不相关的说法:“ClientConnectionReady”variables可能应该写成一个函数定义:

 function ClientConnectionReady(client) { // ... } 

否则应该用var声明。 (我有点惊讶,事实上它不是抛出一个错误,但是我不再那么熟悉Node.js.)

通过它的外观,你正试图写最后的分配值。

我假设client.query是asynchronous的。 鉴于此,callback函数很可能是在res.writeHeadres.write行之后调用的。 你需要做的是把第一个callback中的其他调用和client.write*行。

这应该给你一个想法(没有检查是否编译)

 ClientConnectionReady = function(client) { var final = ''; //Get the rows client.query('select * from table', function selectCb(error, result, fields) { if (error) { console.log('ERROR'); client.end(); return; } final+="{"+JSON.stringify(result); //Get the count query client.query("SELECT COUNT(*) from table", function selectCb(error, result, fields) { if (error) { console.log('ERROR'); client.end(); return; } final+=","+JSON.stringify(result)+"}"; //Return the final results to the client now res.writeHead(200, {'Content-Type': 'text/plain'}); res.write(final); res.end(); client.end(); }); }); }; 

这是做什么是第一次获得行。 在这个callback中,它会得到计数。 最后,当它工作时,它将数据发送到客户端计数callback。