【问题标题】:How to access koa ctx object inside knex promise?如何在 knex promise 中访问 koa ctx 对象?
【发布时间】:2019-07-30 07:43:09
【问题描述】:

我正在使用 KnexJS 承诺查询数据库。我能够在async/await 中获得结果,但是当我使用 Knex 承诺时,我无法访问承诺中的then 和catch 部分的ctx 对象。 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")
  })

})

【问题讨论】:

  • 为什么不想使用 Async/await?
  • 因为为什么不呢? @technogeek1995

标签: knex.js koa


【解决方案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")
      })
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 2015-02-20
    • 2020-04-11
    • 1970-01-01
    • 2018-06-05
    • 2016-03-26
    • 2021-01-24
    相关资源
    最近更新 更多