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
console.log(i, 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()
标签:taskUtils,console,log,模型,任务,next,洋葱,currentIndex,._ From: https://www.cnblogs.com/stof/p/17747026.html