Node.js从MySQL查询返回结果
我有以下函数从数据库中获取一个hex代码
function getColour(username, roomCount) { connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result) { if (err) throw err; return result[0].hexcode; }); }
我的问题是,我在callback函数中返回结果,但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
的值
你必须对callback中的数据库查询结果进行处理。 就像。
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); } });