我一直在尝试对节点中的MySQL使用async / await,但是每次它都会返回一个未定义的值。有什么理由吗?请在下面找到我的代码。
const mysql = require('promise-mysql');
var connection;
const dbConfig = {
host: "hostname",
database: "dbname",
user: "username",
password: "passwords"
};
async function getResult(){
await mysql.createConnection(dbConfig).then(function(conn){
connection = conn;
var result = connection.query('select height from users where pin=1100');
return result;
}).then(function(rows){
console.log(JSON.parse(JSON.stringify(rows[0].height)));
connection.end();
return rows[0].height;
}).catch(function(error){
if (connection && connection.end) connection.end();
//logs out the error
console.log(error);
});
}
async function queryDb(){
try{
var height = await getResult();
console.log(height);
if(height){
console.log(height)
}
}catch(err){
console.log(err);
console.log('Could not process request due to an error');
return;
}
}
queryDb();
我希望将高度返回到queryDb中,但是,该值仅显示在getResult函数中,而不会返回以在queryDb函数中使用。
我知道代码可能并不完美,因为我是Node的新手,我一直在尝试寻找其他方法来做到这一点,但是
答案 0 :(得分:4)
async function getResult(){
let connection;
try {
connection = await mysql.createConnection(dbConfig);
const result = await connection.query('select height from users where pin=1100');
console.log(result[0].height);
return result[0].height;
} finally {
if (connection && connection.end) connection.end();
}
}
解决以下问题:
then
是没有意义的。stringify
和parse
。getResult
的函数不会返回垃圾/ undefined
。我没有抛出它,而是添加了一个finally
块,该块始终关闭连接,无论连接是否成功。let
和const
。比var
=)