编辑代码

class TaskScheduler{

    constructor(){
        this.max = 2
        this.cur = 0
        this.list = []
    }

    run(){
        if(this.cur<this.max&&this.list.length>0){
            this.cur++
            const task = this.list.shift()
            task().finally(()=>{
                this.cur--
                this.run()
            })
        }
        else{
            return
        }
    }

    addTask(fn){
        return new Promise(()=>{
            this.list.push(()=>Promise.resolve().then(fn()))
            this.run()
        })
    }
}


let scheduler = new TaskScheduler()

function promiseTimeout(time,label){
    console.time(label)
    return ()=>{
        new Promise((resolve)=>{
            setTimeout(()=>{
                resolve()
            },time)
        }).then(()=>{
            console.timeEnd(label)
        })
    }
}

scheduler.addTask(promiseTimeout(1000,"1"))
scheduler.addTask(promiseTimeout(2000,"2"))
scheduler.addTask(promiseTimeout(3000,"3"))
scheduler.addTask(promiseTimeout(4000,"4"))