我一直在尝试在node中使用async/await和MySQL,但每次都返回undefined值。这是为什么?请看下面我的代码。
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函数中使用。
我知道代码可能不完美,因为我是新手,并一直在尝试找到替代方法来完成此操作,但是...
getResult
函数没有返回任何内容。 - user5734311