koa的 await next()解释

koa await next()

根据官方介绍:以 “Hello World” 的响应作为示例,当请求开始时首先请求流通过 x-response-timelogging 中间件,然后继续移交控制给 response 中间件。当一个中间件调用 next() 则该函数暂停并将控制传递给定义的下一个中间件。当在下游没有更多的中间件执行后,堆栈将展开并且每个中间件恢复执行其上游行为。

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

// x-response-time
app.use(async (ctx, next) => {
    const start = Date.now();
    console.log('------1---------');
    await next();
    console.log('------2---------');

    const ms = Date.now() - start;
    ctx.set('X-Response-Time', `${ms}ms`);
});

// logger
app.use(async (ctx, next) => {
    const start = Date.now();
    console.log('------3--------');

    await next();
    console.log('------4---------');

    const ms = Date.now() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

app.use(async (ctx, next) => {
    console.log('------5--------');

    await next();
    console.log('------6---------');

});

// response
app.use(async ctx => {
    console.log('------7---------');

    ctx.body = 'Hello World';
});

app.listen(30000);

打印结果;
------1---------
------3--------
------5--------
------7---------
------6---------
------4---------
GET / - 2
------2---------
------1---------
------3--------
------5--------
------7---------
------6---------
------4---------
GET /favicon.ico - 0
------2---------

posted @ 2021-02-25 20:01  古怪精灵  阅读(1724)  评论(0编辑  收藏  举报