s2t*_*2t2 7 node.js express knex.js
将 knex 与 express 结合使用,如何访问 knex 查询的结果?
例子:
var bots = []
response = knex.select('id', 'name').from('robots')
.then(function(robots){
console.log(robots);
bots = robots
});
console.log(bots)
Run Code Online (Sandbox Code Playgroud)
这将记录机器人但不会更新bots数组,该数组为空。
编辑:
作为同步解决方法,在快速路由中,我将快速块卡在 knex 块内:
router.get('/robots', function (req, res) {
response = knex.select('id', 'name').from('robots').then(function(bots){
res.render('robots/index', {
page_title: 'All Robots',
robots: bots
}); // res.render
}); // knex.select
}); // router.get
Run Code Online (Sandbox Code Playgroud)
这是推荐的模式吗?
knex使用承诺。具体来说,它使用http://bluebirdjs.com/docs/getting-started.html。console.log(bots)不会工作,因为它是立即调用的,而.then( ... )仅在knex查询成功调用并运行后才调用。
您编辑的“同步解决方法”是运行快速响应的正确方法,尽管您不需要将该查询设置为var response(有关更多信息,请参阅我对您的问题的评论)。
| 归档时间: |
|
| 查看次数: |
17118 次 |
| 最近记录: |