問題描述
你好朋友,我是 node js 的新手,我們?nèi)绾潍@取 mysql 查詢匿名函數(shù)中使用的變量值?
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();
在上面的代碼中,當(dāng)使用console.log(output)給出正確的結(jié)果時,在client.query中我沒有發(fā)現(xiàn)返回輸出結(jié)果,但不能訪問匿名函數(shù)之外的輸出值.
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.
請幫幫我
提前致謝.
推薦答案
您將無法在回調(diào)函數(shù)之外訪問該變量.原因是,Node.js 有一個特殊功能,即在執(zhí)行異步 IO 任務(wù)(在您的情況下為 mysql 查詢)后,將回調(diào)函數(shù)作為下一個要執(zhí)行的代碼塊傳遞.
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).
當(dāng)您的程序進(jìn)入 IO 模式時,您在回調(diào)函數(shù)之后編寫的代碼會立即執(zhí)行.并且 output
變量直到回調(diào)被觸發(fā)才準(zhǔn)備好.因此您無法訪問它.
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.
您可以在此處
您必須在該回調(diào)函數(shù)中使用 output
或在那里調(diào)用其他函數(shù)并將 output
作為參數(shù)傳遞給它.
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.
這篇關(guān)于如何在節(jié)點(diǎn) js mysql 查詢函數(shù)中找到匿名函數(shù)之外的返回變量值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!