任务执行的洋葱模型

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

 

posted @ 2023-10-07 17:30  爱编程的小小苏  阅读(26)  评论(0)    收藏  举报