Node.js 在 mysql 中使用 async/await [英] Node.js Using async/await with mysql

查看:84
本文介绍了Node.js 在 mysql 中使用 async/await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在 node 中对 MySQL 使用 async/await,但它每次都返回一个未定义的值.有什么原因吗?请在下面找到我的代码.

I've been trying to use async/await with MySQL in node but it returns an undefined value each time. Is there a reason why? Please find my code below.

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 函数中使用.

I expect the height to be returned in queryDb, however, the value is only shown in the getResult function and not returned to be used in the queryDb function.

我知道代码可能并不完美,因为我是 node 的新手,我一直在尝试寻找其他方法来做到这一点,但是

I know the code may not be perfect as I'm new to node and I've been trying to find alternative ways to do this but

推荐答案

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. 你没有返回任何东西.
  1. If you can use async/await, it's pointless to still use then for these situations..
  2. You don't need to JSON stringify and parse if you're logging something.
  3. If you catch an error to close a connection, you really should rethrow it so the function that calls getResult doesn't get garbage/undefined back. Instead of rethrowing it, I just added a finally block that always closes the connection, whether it was successful or not.
  4. Since you're using async/await, your javascript engine should support let and const. It's better than var =)
  5. You weren't returning anything.

这篇关于Node.js 在 mysql 中使用 async/await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆