你好朋友,我是 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.
这篇关于如何在节点 js mysql 查询函数中找到匿名函数之外的返回变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
获取所有产品、类别和元数据的 SQL 查询 woocommSQL query to get all products, categories and meta data woocommerce/wordpress(获取所有产品、类别和元数据的 SQL 查询 woocommerce/wordpre
如何在 WSL(Linux 的 Windows 子系统)中使用 MySQL?How to use MySQL in WSL (Windows Subsystem for Linux)?(如何在 WSL(Linux 的 Windows 子系统)中使用 MySQL?)
任务计划程序中的 PowerShell MySQL 备份脚本错误 PowerShell MySQL Backup Script Error in Task Scheduler 0x00041301(任务计划程序中的 PowerShell MySQL 备份脚本错误 0x00041301)
将数据从 XML 文件导入 MySQL 数据库Import the data from the XML files into a MySQL database(将数据从 XML 文件导入 MySQL 数据库)
在 Windows 7 32 位上安装 Xampp.启动时的错误installed Xampp on Windows 7 32-bit. Errors when starting(在 Windows 7 32 位上安装 Xampp.启动时的错误)
Windows xampp 上的 Mysql 小写表Mysql lower case table on Windows xampp(Windows xampp 上的 Mysql 小写表)