Koa: ctx.body randomly not working

Created on 16 May 2018  路  3Comments  路  Source: koajs/koa

route(path, callback) {
  this.router.get('/' + path, async (ctx, next) => {
    ctx.status = 200;
    ctx.body = 'GET ' + '/' + path + ' is online!';
    if (callback && typeof callback === 'function') await callback(ctx, next);
  });
}

this.route(name, async (ctx) => {
  await MongoModel.find({}, async (err, objects) => {
    ctx.status = 200;
    ctx.body = objects;
    if (err)
      ctx.body = 'Mongo Error';
  })
});

Any idea of why this code shows randomly either the result of:
ctx.body = 'GET ' + '/' + path + ' is online!';
either the result of:
ctx.body = objects;
when objects is ALWAYS set? (checked with console log).
Honestly, I don't get it.

question

All 3 comments

Sorry, there's insufficient information to be able to debug this. Common mistakes are having conflicting route paths or not calling and return/await next(). I recommend you to try stepping through your code find a way to consistently recreate diff.

I'm going to close this due to inactivity. But if you come back with the same issue and more information regarding your problem feel free to reopen!

Solved the issue.

First, I'll apologize for a couple of things:

  • My code from the original issue came from a much broader project that I'm working on, and it wasn't testable as it was
  • I didn't answer for some time

Then, here is the correct way to handle the need of a callback inside a routed path. Promise usage was needed.

function route(path, callback) {
  this.router.get('/' + path, async (ctx, next) => {
    ctx.status = 200;
    if (callback && typeof callback === 'function')
      ctx.body = callback(ctx, next);
  });
}

async function myCallback(ctx, next) {
  return new Promise(resolve => {
    resolve('This will be printed in ctx.body';
  });
}

And then you just call:
route('mypath', myCallback);

Thanks anyway, @fl0w

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sibelius picture sibelius  路  3Comments

ke1Del picture ke1Del  路  3Comments

ilkkao picture ilkkao  路  4Comments

ElegantScripting picture ElegantScripting  路  5Comments

rainesinternationaldev picture rainesinternationaldev  路  5Comments