Pat*_*tle 22 mysql callback node.js
我有以下函数从数据库中获取十六进制代码
function getColour(username, roomCount)
{
connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)
{
if (err) throw err;
return result[0].hexcode;
});
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我在回调函数中返回结果,但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;
}
Run Code Online (Sandbox Code Playgroud)
但当然SELECT查询已经在返回值时完成了 colour
mit*_*esh 53
您必须仅在回调上对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);
}
});
Run Code Online (Sandbox Code Playgroud)
如果您想使用Promise来避免所谓的“回调地狱”,有多种方法。
这是一个使用本机承诺和标准MySQL包的示例。
const mysql = require("mysql");
//left here for testing purposes, although there is only one colour in DB
const connection = mysql.createConnection({
host: "remotemysql.com",
user: "aKlLAqAfXH",
password: "PZKuFVGRQD",
database: "aKlLAqAfXH"
});
(async () => {
connection.connect();
const result = await getColour("username", 2);
console.log(result);
connection.end();
})();
function getColour(username, roomCount) {
return new Promise((resolve, reject) => {
connection.query(
"SELECT hexcode FROM colours WHERE precedence = ?",
[roomCount],
(err, result) => {
return err ? reject(err) : resolve(result[0].hexcode);
}
);
});
}
Run Code Online (Sandbox Code Playgroud)
在异步函数中,您可以使用await表达式暂停函数执行,直到 Promise 被解析或拒绝。这样,该getColour函数将返回一个带有 MySQL 查询的承诺,这将暂停主函数的执行,直到返回结果或抛出查询错误。
一种类似但可能更灵活的方法可能是使用MySQL 库的承诺包装器包,甚至是基于承诺的 ORM。
| 归档时间: |
|
| 查看次数: |
58234 次 |
| 最近记录: |