本文介绍了Node.js返回MySQL查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下函数从数据库获取一个十六进制代码
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;
});
}
$ b $ p我的问题是我在回调函数中返回结果,但getColour函数不返回任何内容。我想让getColour函数返回 result [0] .hexcode
的值。
在我调用getColour的时候它不返回任何东西
At the moment when I called getColour it doesn't return anything
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查询已经完成时返回 color
but of course the SELECT query has finished by the time return the value in colour
推荐答案
你必须对db的结果进行处理仅查询回调。就像
You have to do the processing on the results from the db query on a callback only. Just like.
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);
}
});
这篇关于Node.js返回MySQL查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!