SOURCE

class Scheduler {
    constructor() {
        this.maxVol = 2;
        this.curVol = 0;
        this.tasks = [];
    }

    add(promiseCreator) {
        // console.log(this.curVol);
        return new Promise((resolve, reject) => {
            this.tasks.push({promiseCreator, resolve, reject});
            // console.log(this.tasks);
            this._run();
        })
    }

    _run() {
        while (this.curVol < this.maxVol && this.tasks.length) {
            const {promiseCreator: creator, resolve, reject} = this.tasks.shift();
            // console.log(this.tasks);
            this.curVol++;
            creator().then(resolve, reject).finally(() => {
                    this.curVol--;
                    this._run();
                })
        }
    }
}

const scheduler = new Scheduler();

function timeout(time) {
    return () => {
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve();
            }, time);
        });
    }
}

function addTask(time, order) {
    scheduler.add(timeout(time)).then(() => console.log(order));
}

addTask(1000, '1');
addTask(500, '2');
addTask(300, '3');
addTask(400, '4');

// class A{
//     constructor() {
//         this.init = 0;
//     }

//     add() {
//         this.init++;
//         console.log(this.init);
//     }
// }

// const a = new A();
// a.add();
// a.add();
console 命令行工具 X clear

                    
>
console