js中间件的思维

在原生nodejs中,在监听响应的时候我们需要不断的去判断url,来响应不同的处理方式,这就会造成代码的很难去维护,

在express总就采用了中键的设计角度去思考,其中利用了next递归方式去调用,而this.cache相当于代理作用保存了所有中间键的方法.设计非常巧妙

function Middle(){
      this.cache=[];
  }
  Middle.prototype.use=function(fn){
      if(typeof fn!="function"){
          console.error("你传入的不是一个方法")
      }
      this.cache.push(fn);
  }
  Middle.prototype.next=function(){
    if(this.middles.length==0||!this.middles){
        return
    }
    var fn=this.middles.shift();
    fn.call(this,this.next.bind(this));
  }
  Middle.prototype.commit=function(){
      this.middles=this.cache.slice();
      this.next()
  }
  var middle=new Middle();
  middle.use(function(next){
    console.log(1);  
    next();
  })
  middle.use(function(next){
    console.log(2);  
    next();
  })
  middle.use(function(next){
    console.log(3);
  })
  middle.use(function(next){
    console.log(4);  
    next();
  })
  middle.commit()
  middle.commit()

 

转载于:https://www.cnblogs.com/520lqlst/p/11179434.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值