javascript - Node.JS 异步调用mySql

标签 javascript mysql node.js asynchronous es6-promise

因此,我尝试在我的 node.js 项目中进行 getConnection 和异步查询,因为我只想在查询后呈现响应。这是代码,

router.post('/', function(req, res, next) {

  var queryRows;

  con.getConnection(function(error, connection) {
    if(error) {
    } else {
      connection.query('SELECT * FROM Tablee', function(error, rows, fields){
        queryRows = rows;
      });
    }
  });

  res.render('home', {data:queryRows});
}

我想先运行 getConnection() 和代码;然后渲染。

我遵循了此 Question 中给出的确切解决方案,但徒劳无功。 连接本身是未定义的;所以查询返回错误。

我正在使用 Node 版本 8 来支持异步和等待;但是我无法得到结果。

最佳答案

mysql 不支持 promise ,这是能够使用 async/await 的要求。

而不是使用 util.promisify 包装它或类似的东西,你可以考虑将你的代码迁移到 mysql2,它支持开箱即用的 promise :https://github.com/sidorares/node-mysql2#using-promise-wrapper

由于 mysql2 试图提供与 mysql 相同的 API,因此代码更改应该最少。

编辑:一些(未经测试的)示例代码:

// Install an Express middleware that will set up the database connection, if required.
// Call this somewhere "high up" in your Express app, before route declarations.
app.use(async (req, res, next) => {
  if (! app.db) {
    const mysql = require('mysql2/promise');
    app.db = await mysql.createConnection({ ... });
    // instead of .createConnection, you can also use .createPool
  }
  req.db = app.db;
  return next();
});

然后在你的 route :

router.post('/', async function(req, res) {
  let [ queryRows, queryFields ] = await req.db.query('SELECT * FROM Tablee');
  res.render('home', { data : queryRows });
}

(为简洁起见,我省略了所有错误处理,不过请务必添加它)

关于javascript - Node.JS 异步调用mySql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45658061/

相关文章:

javascript - 如何在文本框中将 "&"更改为 "&"?

mysql - SQL 语句按问题排序

mysql - 从 MySql 导出结果集为制表符分隔文件。带逗号的字符串在字符串周围有引号,为什么?

javascript - 尽管已发送结果,但 Node + Express 反复触发/循环请求

javascript - 如何在 keycloak Admin API 中使用用户数据获取领域角色

javascript - 提交前的图像预览在 IE 9 和 Safari 5.x 中不起作用

javascript - 打破nodejs中的循环

mysql - 数据库设计 - MySQL : How to store and split time series

javascript - Socket.io 消息未附加

HTML 元素的 Javascript 字符串表示