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

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

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

  1. const mysql = require('promise-mysql');
  2. var connection;
  3. const dbConfig = {
  4. host: "hostname",
  5. database: "dbname",
  6. user: "username",
  7. password: "passwords"
  8. };
  9. async function getResult(){
  10. await mysql.createConnection(dbConfig).then(function(conn){
  11. connection = conn;
  12. var result = connection.query('select height from users where pin=1100');
  13. return result;
  14. }).then(function(rows){
  15. console.log(JSON.parse(JSON.stringify(rows[0].height)));
  16. connection.end();
  17. return rows[0].height;
  18. }).catch(function(error){
  19. if (connection && connection.end) connection.end();
  20. //logs out the error
  21. console.log(error);
  22. });
  23. }
  24. async function queryDb(){
  25. try{
  26. var height = await getResult();
  27. console.log(height);
  28. if(height){
  29. console.log(height)
  30. }
  31. }catch(err){
  32. console.log(err);
  33. console.log('Could not process request due to an error');
  34. return;
  35. }
  36. }
  37. queryDb();

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

c2e8gylq

c2e8gylq1#

  1. async function getResult(){
  2. let connection;
  3. try {
  4. connection = await mysql.createConnection(dbConfig);
  5. const result = await connection.query('select height from users where pin=1100');
  6. console.log(result[0].height);
  7. return result[0].height;
  8. } finally {
  9. if (connection && connection.end) connection.end();
  10. }
  11. }

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

展开查看全部

相关问题