简易版实现中几点必须的操作:
- 一个array middleList 来存储中间件
- 执行中间件的操作,循环 middleList 将每一项执行,或者使用shift 将切出的每一项执行
- 有next 、 done 函数
- 初始执行next
class MiddleWare { constructor(data) { this.data = data; this.middleList = []; this.next = this.next.bind(this) this.done = this.done.bind(this) } use(middle) { if (typeof middle !== 'function') { throw 'middle is not a function' return; } this.middleList.push(middle) } next() { if (this.middleList.length > 0) { let cur = this.middleList.shift(); cur(this.data, this.next, this.done) } else { this.done() } } done() { this.middleList = []; console.log('全部执行完毕'); } } const fn1 = (data, next, done) => { console.log('this is fn1', data); setTimeout(() => { next(); }, 2000); } const fn2 = (data, next, done) => { console.log('this is fn2', data); // done() next(); } const fn3 = (data, next, done) => { console.log('this is fn3', data); next(); } const data = '123' // 传入参数 let list = new MiddleWare(data); list.use(fn1) list.use(fn2) list.use(fn3) list.next()
文章评论