Node.js与MySQL一起使用async / await

时间:2018-08-23 12:03:01

标签: javascript mysql node.js promise async-await

我一直在尝试对节点中的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的新手,我一直在尝试寻找其他方法来做到这一点,但是

1 个答案:

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

}

解决以下问题:

  1. 如果您可以使用async / await,在这些情况下仍然使用then是没有意义的。
  2. 如果您要记录某些内容,则无需使用JSON stringifyparse
  3. 如果在关闭连接时遇到错误,则应该重新抛出该错误,以使调用getResult的函数不会返回垃圾/ undefined。我没有抛出它,而是添加了一个finally块,该块始终关闭连接,无论连接是否成功。
  4. 由于您正在使用异步/等待,因此您的JavaScript引擎应支持letconst。比var =)
  5. 您什么都没退。