任务执行的洋葱模型

发布时间 2023-10-07 17:36:03作者: 爱编程的小苏苏
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()