Node.js使用async/await与mysql配合使用

3

我一直在尝试在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函数中使用。

我知道代码可能不完美,因为我是新手,并一直在尝试找到替代方法来完成此操作,但是...


1
你的 getResult 函数没有返回任何内容。 - user5734311
@ChrisG 谢谢,那是我很愚蠢的一部分。 - Jay
1个回答

7
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. 你没有返回任何东西。

感谢您的帮助。在最后实际返回某些内容后,代码已经起作用了。您的修改非常有见地,但由于行没有被记录,所以并没有起作用。 - Jay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接