【问题标题】:Strange issue with async function in KoaKoa 中异步函数的奇怪问题
【发布时间】:2018-01-24 14:48:43
【问题描述】:

代码片段如下:

//Category.service.js
...
exports.update = async (ctx, next) => {
  const {categoryId} = ctx.params
  const _category = ctx.request.body
  // ctx.body = {key: 'test'}
  const category = await Category.get(categoryId)
  console.log(category)
  ctx.body = await category.update(_category)
  console.log(ctx.response)
}
...

当我发送请求时,它返回“未找到”。但是终端打印正确的结果:

Category {
  id: 1,
  name: 'Javascript',
  description: 'This is a test for category update.' }
{ status: 404,
  message: 'Not Found',
  header: 
   { 'x-dns-prefetch-control': 'off',
     'x-frame-options': 'SAMEORIGIN',
     'strict-transport-security': 'max-age=15552000; includeSubDomains',
     'x-download-options': 'noopen',
     'x-content-type-options': 'nosniff',
     'x-xss-protection': '1; mode=block',
     vary: 'Accept-Encoding, Origin',
     'access-control-allow-origin': 'chrome-
extension://fhbjgbiflinjbdggehcddcbncdddomop',
     'content-type': 'application/json; charset=utf-8',
     'content-length': '21' },
  body: 
   Category {
     id: 1,
     name: 'Javascript',
     description: 'This is a test for category update.' } }

唯一的问题是状态是404,但是当我尝试这个时:

//Category.service.js
...
exports.update = async (ctx, next) => {
  const {categoryId} = ctx.params
  const _category = ctx.request.body
  ctx.body = {key: 'test'}
  // const category = await Category.get(categoryId)
  // console.log(category)
  // ctx.body = await category.update(_category)
  // console.log(ctx.response)
}
...

一切正常。 Here 是项目的链接。我不知道代码有什么问题。

【问题讨论】:

    标签: javascript node.js ecmascript-6 async-await koa


    【解决方案1】:

    如果 koa 中间件之一不是异步功能。以下将无法正常处理。我的功能之一不是异步功能导致错误。

    【讨论】:

      猜你喜欢
      • 2021-04-01
      • 1970-01-01
      • 2022-10-15
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 2018-05-11
      • 1970-01-01
      相关资源
      最近更新 更多