因此,我尝试在我的 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 });
}
(为简洁起见,我省略了所有错误处理,不过请务必添加它)