KoaJS中间件。返回响应但也调用next()

时间:2018-01-24 06:35:37

标签: node.js koa

我有三个中间件,叫做A,B&下进行。

某些请求是服务器上长时间运行的任务。

在这种情况下,当进入下游时,我希望我的中间件B立即返回通过中间件A上游的HTTP代码202 Accepted。我还需要从中间件B下游调用中间件C.一旦中间件C完成,我想在上游调用它,我也想调用中间件B Upstream(此时,我不在乎是否调用了中间件A上游与否。)

有办法做到这一点吗?

伪代码:

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

/* some routes defined 
//
//
*/

//MW A
app.use(async (ctx,next) => {
    //do something
    await next();
    //do something
});

//MW B
app.use(async (ctx,next) => {
    if (!longRunningTask)    //proceed as normal
        //do something
        await next();
        //do something
    else {
        /* Here I want to return immediately return ctx.status = 202, so it goes upstream through Middleware A, but I also want to invoke next, so that request goes through middleware C's downstream and upstream, as well as middleware B's upstream */

        //return ctx.status = 202;
        //do something
        //await next();
        //so something
    }
});

//MW C
app.use(async (ctx,next) => {
     //do something;
     return;
});

0 个答案:

没有答案