node.js与mysql一起使用async/await

mv1qrgav  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(521)

我一直尝试在node中使用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中返回height,但是,该值只在getresult函数中显示,没有返回到querydb函数中使用。
我知道代码可能并不完美,因为我是新的节点,我一直试图找到其他方法来做到这一点,但

r7s23pms

r7s23pms1#

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();
    }

}

修复了以下问题:
如果可以使用async/await,那么仍然使用它是毫无意义的 then 在这种情况下。。
你不需要这么做 stringify 以及 parse 如果你在记录什么。
如果在关闭连接时发现错误,则确实应该重新触发它,以便调用 getResult 不会有垃圾/ undefined 回来。我没有重复,而是添加了一个 finally 始终关闭连接的块,无论连接是否成功。
因为您使用的是async/await,所以您的javascript引擎应该支持 let 以及 const . 这比 var =)
你什么也没退。

相关问题