简体   繁体   中英

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?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM