class TaskUtils {
constructor() {
this.currentIndex = 0
this.tasks = []
this._isRunning = false
this._next = async () => {
this.currentIndex++;
await this._runTask();
}
}
addTask(task) {
this.tasks.push(task)
}
run() {
if (this._isRunning || !this.tasks.length) {
return
}
this._isRunning = true
this._runTask()
}
async _runTask() {
if (this.currentIndex >= this.tasks.length) {
this._reset()
return;
}
const i = this.currentIndex
const task = this.tasks[this.currentIndex]
await task(this._next)
const j = this.currentIndex
if (i === j) {
await this._next()
}
}
_reset() {
this.currentIndex = 0
this.tasks = []
this._isRunning = false
}
}
const taskUtils = new TaskUtils();
taskUtils.addTask(async (next) => {
console.log('1 start')
await next()
console.log('1 end')
})
taskUtils.addTask( async () => {
console.log('2')
})
taskUtils.addTask( async (next) => {
console.log('3')
await next();
console.log('4')
})
taskUtils.addTask( async () => {
console.log('5')
})
taskUtils.addTask( async (next) => {
console.log('6')
await next();
console.log('7')
})
taskUtils.run()
// 打印顺序
// 1 start
// 2
// 3
// 5
// 6
// 7
// 4
// 1 end