解释洋葱圈模型:
当我们执行第一个中间件时,首先输出1,然后调用next(),那么此时它会等第二个中间件执行完毕才会继续执行第一个中间件。然后执行第二个中间件,输出3,调用next(),执行第三中间件,输出5.此时第三个中间件执行完毕,返回到第二个中间件,输出4,然后返回到第一个中间件。
class TaskPro {
constructor() {
this._TaskList = []
this._isRunning = false
this._currentIndex = 0
// next 函数,要支持异步
this._next = async () => {
this._currentIndex++
await this._runTask()
}
}
// 添加任务函数
addTask(task) {
this._TaskList.push(task)
}
// run 函数
run() {
if(this._isRunning || !this._TaskList.length) return
this._isRunning = true
this._runTask()
}
// 执行任务函数,要支持异步
async _runTask() {
// 当前索引 >= 任务列表长度,表示已全部执行完
if(this._currentIndex >= this._TaskList.length){
this._reset()
return
}
const i = this._currentIndex
const taskItem = this._TaskList[this._currentIndex]
await taskItem(this._next)
const j = this._currentIndex
// 如果执行前的下标和执行后的下标相同,表示没有调用 next() 那么自行调用
if(i === j) {
this._next()
}
}
// 重置函数
_reset() {
this._TaskList = []
this._currentIndex = 0
this._isRunning = false
}
}
const taskPro = new TaskPro()
taskPro.addTask(async (next) => {
console.log(1, '打印测试');
await next()
console.log('1-1', '打印测试');
})
taskPro.addTask(() => {
console.log(2, '打印测试');
})
taskPro.addTask(() => {
console.log(3, '打印测试');
})
taskPro.run()
taskPro.run()
// 最终输出结果
// 1 打印测试
// 2 打印测试
// 3 打印测试
// 1-1 打印测试