如何从查询语句之外的mysql查询中获取值? [英] How to get a value from mysql query outside the query statement?
问题描述
这是该功能,请参见console.log
Here is the function see below 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} ##
The result here is query object Query {domain:null,_events:{error: .. etc} ##
我这样调用:
quo();
推荐答案
tl; dr 一切都发生在回调中.
tl;dr everything happens in a callback.
您正在绊倒Javascript的异步特性.在您的console.log(value);
调用运行时,该查询尚未(必须)完成.因此,当时无法获得查询结果.
You're tripping up on the asynchronous nature of Javascript. By the time your console.log(value);
call runs, the query is not (necessarily) completed. So, there's no way for the result of the query to be available at that time.
许多开发人员使用这样的模式,并在查询结果到来时使用回调函数来处理下一步.
Many developers use a pattern like this, with a callback function to handle the next step when the query result arrives.
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中更易于阅读.但是无论如何,对它们的解释超出了堆栈溢出答案的范围.
Promise
objects make this sort of thing easier to read in node.js. But explaining them is beyond the scope of a Stack Overflow answer anyhow.
这篇关于如何从查询语句之外的mysql查询中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!