asynchronous调用Node.JS上的mySql

所以,我试图在我的node.js项目asynchronousgetConnection和查询,因为我想只在我的查询后,我的回应。 这是代码,

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}); } 

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

我遵循了这个问题的确切解决scheme,但徒劳无功。 连接本身是不确定的; 所以查询返回错误。

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

mysql不支持承诺,这是能够使用async/await

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

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

编辑 :一些(未经testing)示例代码:

 // 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(); }); 

然后在你的路线:

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

(为了简洁,我忽略了所有的error handling,但是确保你添加了它)