如何访问 knex 查询结果

How to access knex query results

将 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

这是推荐的模式吗?

knex 使用承诺。具体来说,它使用 http://bluebirdjs.com/docs/getting-started.htmlconsole.log(bots) 不会起作用,因为它会立即被调用,而 .then( ... ) 只会在 knex 查询成功调用和 运行 之后被调用。

您编辑的 "synchronous workaround" 是 运行 快速响应的正确方法,尽管您不需要将该查询设置为 var response(请参阅我对您的问题的评论更多信息)。

我建议使用 async/await 函数。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

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