Node.js 如何访问knex查询结果

Node.js 如何访问knex查询结果,node.js,express,knex.js,Node.js,Express,Knex.js,使用knex with express,如何访问knex查询的结果 例如: var bots = [] response = knex.select('id', 'name').from('robots') .then(function(robots){ console.log(robots); bots = robots }); console.log(bots) 这将记录机器人,但不会更新机器人数组,该数组为空 编辑: 作为一种同步解决方法,在一条快速路线中,我

使用knex with express,如何访问knex查询的结果

例如:

var bots = []

response = knex.select('id', 'name').from('robots')
  .then(function(robots){
    console.log(robots);
    bots = robots
  });

console.log(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

这是推荐的模式吗?

knex
使用承诺。具体来说,它使用
console.log(bots)
将无法工作,因为它会立即被调用,而
则(…)
只有在
knex
查询成功调用并运行后才会被调用


您编辑的“同步解决方案”是运行Express response的正确方法,尽管您不需要将该查询设置为
var response
(有关这方面的更多信息,请参阅我对您的问题的评论)。

我建议使用异步/等待函数。


then
的函数回调是异步的,基本上它是在db的结果可用时调用的,同时节点继续处理代码(如果有)。我想你们一定注意到了,你们先进入终端,然后是未定义的结果。只需搜索一些关于异步节点的教程,SI不会将
knex
action/query设置为变量(在您的例子中,
response
)。由于
knex
是基于承诺的,因此在
then()
组件中执行并设置变量(或
catch()
错误)。因此,如果您想要一个变量
response
,我会在
knex
数据库查询之前设置
var response
,然后,在
then()
之后和内部,我会根据
knex
查询的结果将
response
设置为您想要的任何值。
router.get('/robots', async function (req, res) {
  const bots = await knex.select('id', 'name').from('robots');
  res.render('robots/index', {
    page_title: 'All Robots',
    robots: bots
  }); // res.render 
}); // router.get