qwang07
qwang07

Reputation: 1256

Strange issue with async function in Koa

Here is the code fragment:

//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)
}
...

When I send a request, It returns 'Not Found'. However the terminal print the correct result:

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.' } }

The only problem is the status is 404, but when I try this one:

//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)
}
...

Everything works fine. Here is the link to the project. I don't know what's wrong with the code.

Upvotes: 1

Views: 117

Answers (1)

qwang07
qwang07

Reputation: 1256

If one of koa middleware is not async function. The following will not process normally. One of my function is not async function cause the error.

Upvotes: 1

Related Questions