[软件设计/软件工程] 如何在 NodeJS 中创建查询 MySQL 的函数?

[复制链接]
发表于 2022-5-6 13:33:56
问题
我这样做了:
  1. const mysql = require('mysql2/promise')

  2. const pool = mysql.createPool({
  3.     host: 'localhost',
  4.     user: 'root',
  5.     password: '',
  6.     database: 'nodejs',
  7.     waitForConnections: true,
  8.     connectionLimit: 10,
  9.     queueLimit: 0
  10. })

  11. async function query(query) {

  12.     const result = await pool.query(query)
  13.     return result[0]

  14. }

  15. console.log(query('SELECT * FROM `users`'))
复制代码

我回来了

承诺{ <待定> }

如何从查询数据库中获取结果,就像 PHP 一样?

在 PHP 中,我从来没有做过像 async/await 和 promises 这样的事情。 . .

我也尝试过使用 mysql:
  1. const mysql = require('mysql')

  2. const db = mysql.createConnection({
  3.     host     : 'localhost',
  4.     user     : 'root',
  5.     password : '',
  6.     database : 'nodejs'
  7. })

  8. function query(query) {
  9.     db.query(query, (err, result) => {
  10.         if (err) throw err
  11.         return result
  12.     })
  13. }

  14. console.log(query('SELECT * FROM `users`'))
复制代码

但我得到一个未定义的结果

回答
我对 MySQL 和您正在使用的库不是很熟悉。

然而,你得到了一个 Promise { <pending> } 响应,因为您没有等待查询执行。

由于该函数被标记为 async 并且还执行异步操作,因此它返回一个需要等待解决的 Promise。

下面的代码应该可以工作:
  1. const mysql = require('mysql2/promise')

  2. const pool = mysql.createPool({
  3.     host: 'localhost',
  4.     user: 'root',
  5.     password: '',
  6.     database: 'nodejs',
  7.     waitForConnections: true,
  8.     connectionLimit: 10,
  9.     queueLimit: 0
  10. })

  11. async function query(query) {

  12.     const result = await pool.query(query)
  13.     return result[0]

  14. }

  15. (async () => {
  16.     const queryResult = await query('SELECT * FROM `users`');
  17.     console.log(queryResult);
  18. } )();
复制代码

要了解 async await 的工作原理,请考虑以下代码:
  1. console.log('I will get printed first');
  2. const asyncFunction = async () => {
  3.    await setTimeout(()=> {}, 1000)
  4.    console.log('I will get printed third');
  5.    return 'hello'
  6. }

  7. (async () => {
  8.   const result = await asyncFunction();
  9.   console.log(`I will get printed last with result: ${result}`);
  10. })();

  11. console.log('I will get printed second');
复制代码

console.log 语句将在执行前等待它完成执行。





上一篇:在图像上为缩小的圆圈设置动画
下一篇:快速查询嵌套可选领域对象的方法

使用道具 举报

Archiver|手机版|小黑屋|吾爱开源 |网站地图

Copyright 2011 - 2012 Lnqq.NET.All Rights Reserved( ICP备案粤ICP备14042591号-1粤ICP14042591号 )

关于本站 - 版权申明 - 侵删联系 - Ln Studio! - 广告联系

本站资源来自互联网,仅供用户测试使用,相关版权归原作者所有

快速回复 返回顶部 返回列表