将业务流程代码中间件化

 

class MidWare{
  constructor(){
    this.cache = [];
  }
  use(fn){
    this.cache.push(fn);
  }
  start(){
    var middles = this.cache;
    function dispatch(index){
      if(index==middles.length){
        return new Promise.resolve();
      }
      return new Promise((resolve,reject)=>{
        resolve(middles[index](()=>dispatch(index+1)));
      })
    }
    return dispatch(0);
  }
}

var m = new MidWare();
m.use(function(next){
 console.log(1);
   next();

})

m.use(function(next){
  console.log(2);
  next();
})

m.use(function(next){
  console.log(3);
  next();
})

m.start()

 

posted @ 2019-03-20 16:17  abc1234_abc  阅读(192)  评论(0编辑  收藏  举报