SOURCE


class Queue {
    constructor({ arr, func, limit = 6 }) {
        this.count = 0
        this.arr = arr
        this.limit = limit
        this.func = func
        this.loop()
    }
    async loop() {
        console.log(this.count)
        this.count += 1
        const finish = () => {
            if (!!this.arr.length) {
                this.loop()
            } else {
                console.timeEnd('test')
            }
        }
        if (this.count < this.limit) {
            this.func(this.arr.shift())
            finish()
        } else {
            await this.func(this.arr.shift())
            finish()
        }

    }
    resolve() {
        this.count -= 1
    }
}


const arr = Array(20).fill().map((v, i) => i)
console.time('test')
const queue = new Queue({ arr, func: promiseFunc })
function promiseFunc(props) {
    return new Promise((resolve) => {
        setTimeout(() => {
            queue.resolve()
            resolve()
            console.log(props, 'props')
        }, Math.random() * 1000 + 1000)
    })
}

console 命令行工具 X clear

                    
>
console