如何在节点 js mysql 查询函数中找到匿名函数之外的返回变量值

你好朋友,我是 node js 的新手,我们如何获取 mysql 查询匿名函数中使用的变量值?

Hello friend i am new in node js, how we can get variable value used in mysql query anonymous function ?

var alldata = function(){

var http = require('http'), mysql = require('mysql');

var client = mysql.createConnection({
       host: '127.0.0.1',
   user: 'root',
   password: ''
});

client.connect();
client.query("use cakephp2");

client.query("SELECT id, title,body,created from posts", 
        function(err, results, fields) {
            if (err) throw err;

            var output = '<h1>Latest Posts</h1><ul><table border=1><tr>';
            for (var index in fields) {
                output += '<td>' + fields[index].name + '</td>';
            }
            output += '</tr>';
            for (var index in results) {
                output += '<tr><td>' + results[index].id + '</td>';
                output += '<td>' + results[index].title + '</td>';
                output += '<td>' + results[index].body + '</td>';
                output += '<td>' + results[index].created + '</td></tr>';
            }
            output += '</ul>';
            // console.log(output);
            // return output;

        }
    ); 
  return  output ;
}
exports.alldatas = alldata();

在上面的代码中,当使用console.log(output)给出正确的结果时,在client.query中我没有发现返回输出结果,但不能访问匿名函数之外的输出值.

in above code i did not found return output result while in client.query when use console.log(output) give correct result, but can not access output value outside of anonymous function.

请帮帮我

提前致谢.

推荐答案

您将无法在回调函数之外访问该变量.原因是,Node.js 有一个特殊功能,即在执行异步 IO 任务(在您的情况下为 mysql 查询)后,将回调函数作为下一个要执行的代码块传递.

You won't be able to access that variable outside the callback function. The reason is, the Node.js has a special feature of passing a callback function as the next block of code to be executed after performing an asynchronous IO task, (in your case a mysql query).

当您的程序进入 IO 模式时,您在回调函数之后编写的代码会立即执行.并且 output 变量直到回调被触发才准备好.因此您无法访问它.

The code you write after the callback function gets executed immediately when your program goes into IO mode. And the output variable is not ready untill the callback is fired. and hence you can not access it.

您可以在此处

您必须在该回调函数中使用 output 或在那里调用其他函数并将 output 作为参数传递给它.

You will have to ue the output within that callback function or call some other function there and pass output to it as a parameter.

相关文章