【发布时间】:2016-03-20 07:51:58
【问题描述】:
将 knex 与 express 结合使用,我如何访问 knex 查询的结果?
例子:
var bots = []
response = knex.select('id', 'name').from('robots')
.then(function(robots){
console.log(robots);
bots = robots
});
console.log(bots)
这将记录机器人,但不会更新空的bots 数组。
编辑:
作为一种同步解决方法,在快速路由中,我将 express 块卡在 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
这是推荐的模式吗?
【问题讨论】:
-
then的回调函数是异步的,基本上它是在 db 的结果可用时调用的,如果同时有任何代码,节点会继续处理您的代码。我想你一定已经注意到你首先进入终端 undefined 然后结果。随便搜一些关于 async nodejs 的教程 -
我不会将
knex操作/查询设置为变量(在您的情况下为response)。因为knex是基于Promise 的,所以在then()组件中执行和设置变量(或catch()用于错误)。所以,如果你想要一个变量response,我会在knex数据库查询之前设置var response,然后在then()之后和内部,我会将response设置为你想要的任何东西knex查询的结果。