【问题标题】:How to write a async middleware in KOA 2如何在 KOA 2 中编写异步中间件
【发布时间】:2017-05-23 09:44:12
【问题描述】:

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

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

【问题讨论】:

  • 如何声明这个函数供koa使用? koa.use(render) ?
  • @OvidiuDolha 是的,我正在导出这个中间件并做一个const app = new Koa(); app.use(render)
  • 如果你遇到koa.use((ctx, next) => render(ctx, next))同样的问题,只是好奇?
  • 没关系,我只是在一个简单的 koa 种子 (github.com/chentsulin/simple-koa2-example) 上复制了您的示例,并且效果很好……问题一定出在其他地方。您在应用程序中还有哪些其他中间件?另外:你如何启动服务器?你使用的是什么版本的节点?
  • @OvidiuDolha 我也尝试使用您链接到的 simple-koa 示例。在 router.js 文件中添加 : await new Promise((resolve) => { setTimeout(resolve, 10000) }) 会导致立即返回,即由于某种原因,不会发生 10 秒的等待

标签: javascript node.js async-await koa koa2


【解决方案1】:

我意识到我在这里晚了几个月,但我刚刚偶然发现了同样的问题,并发现为了让给定的中间件能够等待异步执行,前面的所有中间件都必须@ 987654321@,而不仅仅是next()。确保验证这一点,事后看来是显而易见的。

我希望这会有所帮助。

【讨论】:

  • 天哪,终于,经过数小时的搜索。非常感谢!
【解决方案2】:

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

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 函数的方式在某种程度上是不正确的。

【讨论】:

    【解决方案3】:

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

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-18
      • 2016-10-03
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      相关资源
      最近更新 更多