Javascript 如何在膝关节炎2中编写异步中间件 我想解决一个承诺,然后在膝关节炎2中提出这样的观点。< /P> 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() }

Javascript 如何在膝关节炎2中编写异步中间件 我想解决一个承诺,然后在膝关节炎2中提出这样的观点。< /P> 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() },javascript,node.js,async-await,koa,koa2,Javascript,Node.js,Async Await,Koa,Koa2,但是,当我这样做时,服务器不会发送任何响应(浏览器一直在等待响应,然后超时)。我做错了什么?所以,我用你的代码创建了一个小应用程序: 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(r

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

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

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

这是开箱即用的方式。。。不需要改变。因此,您“使用”呈现函数的方式似乎有点不正确。

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


我希望这能有所帮助。

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

希望它能帮助你< /p>你如何声明这个函数被膝关节炎使用?code>koa.use(render)?@OvidiuDolha是的,我正在导出此中间件并执行
const-app=new-koa();膝关节炎。使用(渲染)< /COD>只是古玩,如果你做了代码>膝关节炎。使用((CTX,NEXT)= >渲染(CTX,NEXT))< /C>同样的问题。没关系,我只是复制了你的例子,在一个简单的KOA种子()上,并且工作得很好…问题一定出在别的地方。应用程序中还有哪些其他中间件?另外:如何启动服务器?您使用的node版本是什么?@OvidiuDolha我也尝试使用您链接到的简单koa示例。在router.js文件中添加一个:wait new Promise((resolve)=>{setTimeout(resolve,10000)})会导致立即返回,也就是说,由于某种原因,经过数小时的搜索,10秒的等待最终不会发生。非常感谢你!