問題描述
你好朋友,我是 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模板網!