中间件的实现

94 阅读1分钟
class Middleware {
	constructor(){
	this.arr=[]
	this.no=0
	}
	use(fn){
	this.arr.push(fn.bind(this))
	}
	go(fn){
	fn?this.res=fn:this.res=function(){console.log('初始GO')}
	this.next()
	}
	next(fn){
	if(this.no==this.arr.length){
	this.res()
	return
	}
	this.arr[this.no](this.next.bind(this))
	this.no++
	}
}
var middleware=new Middleware()
var time =new Date()
middleware.use(next=>{
	setTimeout(()=>{
	this.hook1=true
	next()
	},10)
})
middleware.use(next=>{
	setTimeout(()=>{
	this.hook2=true
	next()
	},10)
})
middleware.go()