• 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---------
    
    
  • 相关阅读:
    Discuz利用百度ping把我们网站自动提交到百度
    正则表达式速查表1
    thinkphp 新浪新闻采集代码演示
    php采集一网站的精美图片
    百度知道的php爬虫
    新浪新闻采集程序
    mysql pid文件丢失解决办法
    js位运算-按位非
    mysql表损坏解决方案
    h5新API之WebStorage解决页面数据通信问题
  • 原文地址:https://www.cnblogs.com/ywnh/p/14448978.html
Copyright © 2020-2023  润新知