zoukankan      html  css  js  c++  java
  • 实现一个简易的express中间件

    代码:

    // 通过闭包实现单例
    const Middlewave = (function(){
        let instance;
        class Middlewave{
            constructor() {
                this.stack = [];    // 中间件调用栈
                return instance || (instance = this);    //    返回单例
            }
            // 注册中间件
            use(...funcs) {
                // 将中间件push到stack调用栈中
                funcs.forEach(func => this.stack.push(func));
            }
            // 调用下一个中间件
            next() {
                if (this.stackCopy[0]) {
                    // 取出当前中间件
                    const curWave = this.stackCopy.shift();
                    // 执行当前中间件
                    // next绑定this,防止this指向被修改
                    curWave(this.req, this.res, this.next.bind(this));
                }
            }
            init(req, res) {
                this.req = req;
                this.res = res;
                // 复制一份中间件调用栈调用栈
                this.stackCopy = this.stack.map(item => item);
                // 执行下一步
                this.next();
            }
        }
        return Middlewave;
    })();

    测试:

    const app = new Middlewave();
    
    function middlewave_a(req, res, next) {
        req.a = true;
        res.a = true;
        console.log('a', req, res);
        next();
    }
    
    function middlewave_b(req, res, next) {
        req.b = true;
        res.b = true;
        console.log('b', req, res);
        next();
    }
    
    function middlewave_c(req, res, next) {
        req.c = true;
        res.c = true;
        console.log('c', req, res);
    }
    
    function middlewave_d(req, res, next) {
        req.d = true;
        res.d = true;
        console.log('d', req, res);
        next();
    }
    
    app.use(middlewave_a);
    app.use(middlewave_b);
    app.use(middlewave_c);
    app.use(middlewave_d);
    
    app.init({name: 'a'}, { name: 'a'});
    app.init({name: 'b'}, { name: 'b'});
    app.init({name: 'c'}, { name: 'c'});

    结果:

  • 相关阅读:
    jmeter导出提取的值或参数化的值到excel
    超级有用的正则表达式
    性能测试监控
    asp.net 多线程
    VS代码格式化快捷键
    JS判断IE版本
    Jquery原创排序table
    将aspx转化为html代码
    Java基本语法——变量
    Entity Framework 中的LazyLoading
  • 原文地址:https://www.cnblogs.com/shenshangzz/p/9687779.html
Copyright © 2011-2022 走看看