【问题标题】:Node.js Using async/await with mysqlNode.js 使用 async/await 和 mysql
【发布时间】: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


【解决方案1】:
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. 由于您使用的是 async/await,因此您的 javascript 引擎应该支持 letconst。比var好多了=)
  5. 您没有返回任何东西。

【讨论】:

  • 感谢您的帮助。在我最后实际返回了一些东西之后,代码才起作用。您的版本很有见地,但由于未记录行而无法正常工作。
猜你喜欢
  • 2019-09-22
  • 2017-10-15
  • 1970-01-01
  • 2018-11-27
  • 2018-07-15
  • 2017-05-29
  • 2019-05-30
  • 2021-12-31
  • 1970-01-01
相关资源
最近更新 更多