【发布时间】:2019-01-29 19:25:27
【问题描述】:
我一直在尝试在节点中将 async/await 与 MySQL 一起使用,但它每次都返回一个未定义的值。有什么原因吗?请在下面找到我的代码。
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 新手,我一直在尝试寻找替代方法来做到这一点,但是
【问题讨论】:
-
你的
getResult函数没有返回任何东西。 -
@ChrisG 谢谢你,这对我来说很愚蠢
标签: javascript mysql node.js promise async-await