这是函数,见下面的console.log
function quo (value){
value = connection.query(
'SELECT role from `roles` where `id` = 1' ,
function (error, results, fields) {
if (error) throw error;
console.log('The role is: ', results[0].role);// result here The role is : admin
});
console.log(value);
}
这里的结果是查询对象Query {domain:null,_events:{error:.. etc} ##
我这样调用它:
quo();
答案 0 :(得分:0)
tl; dr 一切都在回调中发生。
您正在绊倒Javascript的异步性质。当您的console.log(value);
调用运行时,查询不会(必然)完成。因此,当时无法获得查询结果。
许多开发人员使用这样的模式,使用回调函数来处理查询结果到达时的下一步。
function quo (success){
value = connection.query(
'SELECT role from `roles` where `id` = 1' ,
function (error, results, fields) {
if (error) throw error;
console.log('The role is: ', results[0].role);
success (results[0].role);
});
}
quo (function (role) {
console.log(role);
/* do something useful with the role that came back from the query */
});
Promise
个对象使得node.js中的这类内容更容易阅读。但无论如何解释它们都超出了Stack Overflow的范围。
答案 1 :(得分:0)
function quo (success){
value = connection.query(
'SELECT role from `roles` where `id` = 1' ,
function (error, results, fields) {
if (error) throw error;
console.log('The role is: ', results[0].role);
success (results[0].role);
});
}
quo (function (role) {
console.log(role);
/* do something useful with the role that came back from the query */
});