我理解的中间件,就是将流程化的代码抽出来,只要一个输入,返回一个输出,具体中间的逻辑(要第一步做什么,第二步做什么都与我无关)。
class MidWare{ constructor(){ this.cache = []; } use(fn){ if(typeof fn != 'function' ){ return; } this.cache.push(fn); } next(){ if(!this.cache.length){ return; } for(let i=0;i<this.cache.length;i++){ let fn = this.cache.shift(); fn.call(this,this.next); } } do(){ this.use((next)=>{ console.info('第一步'); next.call(this); }); this.use((next)=>{ setTimeout(()=>{ console.info('第二步'); next.call(this); },2000) }); this.use((next)=>{ console.info('结束'); }) this.next(); } } var c = new MidWare(); c.do()