Shubham Kanodia
Shubham Kanodia

Reputation: 6236

How to write a async middleware in KOA 2

I want to resolve a promise and then render a view like so in Koa 2.

async function render(ctx, next) {
  // wait for some async action to finish
  await new Promise((resolve) => { 
   setTimeout(resolve, 5000)
  })
  // then, send response
  ctx.type = 'text/html'
  ctx.body = 'some response'
  await next()
}

However when I do this, the server does not send any response (browser keeps waiting for a response, and times out). What am I doing wrong?

Upvotes: 2

Views: 4801

Answers (3)

m-a-r-c-e-l-i-n-o
m-a-r-c-e-l-i-n-o

Reputation: 2672

I realize that I'm a couple months late here, but I stumbled upon the same issue just now and discovered that in order for a given middleware to be able to wait for async executions, all of the preceding middleware has to await next(), as opposed to just next(). Make sure to verify that, seems obvious in hindsight.

I hope this helps.

Upvotes: 9

Tony
Tony

Reputation: 121

The way I write middleware is pretty similar with @Sebastian:

const Koa = require('koa');
const app = new Koa();

const render = async(ctx, next) {
    // wait for some async action to finish
    await new Promise((resolve) => { 
        setTimeout(resolve, 5000)
    });
    // then, send response
    ctx.type = 'text/html';
    ctx.body = 'some response';

    await next();
}

app.use(render);
....

hope it helps you

Upvotes: 0

Sebastian Hildebrandt
Sebastian Hildebrandt

Reputation: 2771

So, I took your code and created a little app:

const Koa = require('koa');
const app = new Koa();

async function render(ctx, next) {
  // wait for some async action to finish
  await new Promise((resolve) => { 
   setTimeout(resolve, 5000)
  })
  // then, send response
  ctx.type = 'text/html'
  ctx.body = 'some response'
  await next()
}

app.use(render);

app.listen(3000);

This works out of the box this way ... no changes needed. So it seems, the way you "used" your render function was somehow not correct.

Upvotes: 1

Related Questions