因此,我尝试在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来支持异步和等待;但我无法获得结果。
发布于 2017-08-13 15:37:22
mysql
不支持promises,而promises是使用async/await
的必要条件。
您可以考虑将代码迁移到支持promises的开箱即用的mysql2
,而不是使用util.promisify
或类似的东西来包装它:https://github.com/sidorares/node-mysql2#using-promise-wrapper
由于mysql2
试图提供与mysql
相同的应用程序接口,因此代码更改应该最少。
编辑:一些(未经测试的)示例代码:
// 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 });
}
(为简洁起见,我省略了所有错误处理,但请确保添加了它)
https://stackoverflow.com/questions/45658061
复制相似问题