我有以下从数据库中获取十六进制代码的函数
function getColour(username, roomCount)
{
connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)
{
if (err) throw err;
return result[0].hexcode;
});
}
我的问题是我在回调函数中返回结果,但 getColour 函数没有返回任何内容。我希望 getColour 函数返回 result[0].hexcode
的值。
在我调用 getColour 的那一刻,它没有返回任何内容
我试过做类似的事情
function getColour(username, roomCount)
{
var colour = '';
connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)
{
if (err) throw err;
colour = result[0].hexcode;
});
return colour;
}
当然 SELECT 查询已经完成,返回 colour
最佳答案
您必须仅对回调中的 db 查询结果进行处理。就像。
function getColour(username, roomCount, callback)
{
connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)
{
if (err)
callback(err,null);
else
callback(null,result[0].hexcode);
});
}
//call Fn for db query with callback
getColour("yourname",4, function(err,data){
if (err) {
// error handling code goes here
console.log("ERROR : ",err);
} else {
// code to execute on data retrieval
console.log("result from db is : ",data);
}
});
关于mysql - Node.js 从 MySQL 查询返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18361930/