I have the following function that gets a hexcode from the database
我有以下函数从数据库中获取十六进制代码
function getColour(username, roomCount)
{
connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)
{
if (err) throw err;
return result[0].hexcode;
});
}
My problem is that I am returning the result in the callback function but the getColour function doesn't return anything. I want the getColour function to return the value of result[0].hexcode
.
我的问题是我在回调函数中返回结果,但getColour函数不返回任何内容。我希望getColour函数返回result [0] .hexcode的值。
At the moment when I called getColour it doesn't return anything
在我调用getColour时,它不会返回任何内容
I've tried doing something like
我尝试过这样的事情
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;
}
but of course the SELECT query has finished by the time return the value in colour
但当然SELECT查询已经完成了返回颜色值的时间
1 个解决方案
#1
45
You have to do the processing on the results from the db query on a callback only. Just like.
您必须仅在回调上对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);
}
});
#1
45
You have to do the processing on the results from the db query on a callback only. Just like.
您必须仅在回调上对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);
}
});