首页 文章

如何在KOA 2中编写异步中间件

提问于
浏览
0

我想解决一个承诺,然后在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()
}

但是,当我这样做时,服务器不发送任何响应(浏览器一直等待响应,并超时) . 我究竟做错了什么?

3 回答

  • 2

    我意识到我在这里已经晚了几个月了,但我刚才偶然发现同样的问题并发现为了让给定的中间件能够等待异步执行,所有前面的中间件都必须 await next() ,而不是到 next() . 确保事后证实这一点似乎很明显 .

    我希望这有帮助 .

  • 0

    所以,我拿了你的代码并创建了一个小应用程序:

    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);
    

    这种方式开箱即用......无需进行任何更改 . 所以看来,你的 render 函数的方式在某种程度上是不正确的 .

  • 0

    我编写中间件的方式与@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);
    ....
    

    希望它能帮助你

相关问题