如何在Knex Promise中访问Koa ctx对象?

时间:2019-07-30 07:43:09

标签: knex.js koa

我正在使用KnexJS promise查询数据库。我可以在async/await中获得结果,但是当我使用Knex Promise时,无法访问Promise的ctxthen内的catch对象。 console.log(results)在控制台中显示结果。

这是我的代码:

router.get('/profile', async ctx => {

  'http://localhost:8000/profile'

  ctx.knex
    .select().from('profile')

  .then(results => {
    console.error(results)
    this.body = results
  })

  .catch(error => {
    console.log(error)
    this.throw(500, "Inside Error")
  })

})

1 个答案:

答案 0 :(得分:1)

ctx应该可用,因为它是在封闭范围内设置的。

但是您必须从路由器处理程序中返回knex的诺言:

router.get('/profile', ctx => {
  return ctx.knex
      .select().from('profile')

      .then(results => {
        console.error(results)
        this.body = results
      })

      .catch(error => {
        console.log(error)
        this.throw(500, "Inside Error")
      })
});