简体   繁体   English

Node.js变量范围

[英]Node.js Variable scope

I have a http server setup which basically needs to look up stuff in the database. 我有一个http服务器设置,基本上需要在数据库中查找内容。

Here is the code snippet : 这是代码片段:

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");
  

If I print the values of the variable 'final' at the places where I assign them, I see valid values, but at the lines when I do 'res.write(final)', final is still blank. 如果在分配变量的位置打印变量“ final”的值,我会看到有效的值,但是在执行“ res.write(final)”的行中,final仍为空白。

How do I make this work and why is this failing?? 我如何进行这项工作,为什么会失败? Thanks for the help, I am new to node.js 感谢您的帮助,我是node.js的新手

The Node.js environment is asynchronous . Node.js环境是异步的 Those statements that modify "final" are inside callbacks that are executed only when the database operations finish. 这些修改“ final”的语句位于内部回调中,仅在数据库操作完成时才执行。 The code immediately after the initiation of the database operations, where you write the result, are executed long before those callbacks run. 在数据库操作启动之后(即您写入结果的位置)之后立即执行的代码早于这些回调运行之前。

You've almost stumbled upon the answer to the problem already: you must not write the result until the operations are finished, which you know will be the case inside the callbacks. 您已经差点发现了问题的答案:在操作完成之前,您不得写入结果,您将知道回调中的情况。 If you must wait for both to finish (seems like you do), then you can do something like keep a counter in the outer scope. 如果您必须等待两者都完成(似乎像您一样),则可以执行一些操作,例如在外部范围中保留一个计数器。 Each callback can increment the counter, and call the same result-writer function only when the counter indicates that both callbacks are complete. 每个回调都可以递增计数器,并且仅在计数器指示两个回调都已完成时才调用相同的结果编写器函数。 (I have the idea that the Node runtime has a fancier way of doing that sort of thing, but I'm not that familiar with it. In a simple case like this, keeping something like a counter is easy enough to do.) (我的想法是,Node运行时可以做这种事情的方法更高级,但我并不那么熟悉。在这样的简单情况下,保留类似计数器的内容很容易做到。)

Also, an unrelated note: that "ClientConnectionReady" variable should probably either be written as a function definition: 另外,一个不相关的注释:“ ClientConnectionReady”变量可能应该写为函数定义:

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

or else it should be declared with var . 否则应使用var声明。 (I'm a little surprised in fact that it's not throwing an error, but again I'm not that familiar with Node.js.) (实际上,它没有引发错误,我对此感到有些惊讶,但是我对Node.js并不那么熟悉。)

By the looks of it, you are trying to write final before it is ever assigned a value. 从外观上看,您试图在为其赋值之前编写final。

I'm assuming that client.query is asynchronous. 我假设client.query是异步的。 Given that, the callback function is most likely being called after the res.writeHead and res.write lines. 鉴于此,最有可能在res.writeHeadres.write行之后调用回调函数。 What you need to do is put other calls and the client.write* lines within the first callback. 您需要做的是将其他调用和client.write*行放在第一个回调中。

This should give you an idea (didn't check if it compiles) 这应该给您一个想法(没有检查它是否可以编译)

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();
                });
        });                    
};

What this does is first gets the rows. 这首先是获取行。 In that callback, it then gets the count. 然后在该回调中获得计数。 Finally, when that works, it sends the data to the client within the count callback. 最后,当它起作用时,它将在count回调内将数据发送到客户端。

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

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