【问题标题】:How to access knex query results如何访问 knex 查询结果
【发布时间】: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 查询的结果。

标签: node.js express knex.js


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我建议使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多