繁体   English   中英

Node.js变量范围

[英]Node.js Variable scope

我有一个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");
  

如果在分配变量的位置打印变量“ final”的值,我会看到有效的值,但是在执行“ res.write(final)”的行中,final仍为空白。

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

Node.js环境是异步的 这些修改“ final”的语句位于内部回调中,仅在数据库操作完成时才执行。 在数据库操作启动之后(即您写入结果的位置)之后立即执行的代码早于这些回调运行之前。

您已经差点发现了问题的答案:在操作完成之前,您不得写入结果,您将知道回调中的情况。 如果您必须等待两者都完成(似乎像您一样),则可以执行一些操作,例如在外部范围中保留一个计数器。 每个回调都可以递增计数器,并且仅在计数器指示两个回调都已完成时才调用相同的结果编写器函数。 (我的想法是,Node运行时可以做这种事情的方法更高级,但我并不那么熟悉。在这样的简单情况下,保留类似计数器的内容很容易做到。)

另外,一个不相关的注释:“ ClientConnectionReady”变量可能应该写为函数定义:

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

否则应使用var声明。 (实际上,它没有引发错误,我对此感到有些惊讶,但是我对Node.js并不那么熟悉。)

从外观上看,您试图在为其赋值之前编写final。

我假设client.query是异步的。 鉴于此,最有可能在res.writeHeadres.write行之后调用回调函数。 您需要做的是将其他调用和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();
                });
        });                    
};

这首先是获取行。 然后在该回调中获得计数。 最后,当它起作用时,它将在count回调内将数据发送到客户端。

暂无
暂无

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

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