Promises are often seen in asynchronous operations, handling multiple concurrent asynchronous processes. Promises themselves have promises.all () promise.allSettled () promise.race (), etc., but they do not control the number of concurrent processes. This article implements a Schedule class that can be used to control the number of concurrent requests.

Nonsense do not say, on talent ~

class Schedule{

    constructor(maxNum){
        this.list = [];
        this.maxNum = maxNum
        this.workingNum = 0
    }
    
    add(promiseCreator){
        this.list.push(promiseCreator)
    }

    start(){
        for (let index = 0; index < this.maxNum; index++) {
            this.doNext()
        }
    }

    doNext(){
        if(this.list.length && this.workingNum < this.maxNum){
            this.workingNum++;
            const promise = this.list.shift();
            promise().then(() = >{
                this.workingNum--;
                this.doNext(); })}}}const timeout = time= > new Promise((resolve) = >{
    setTimeout(resolve, time)
}) 

const schedule = new Schedule(2);

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

addTask(1000.1)
addTask(500.2)
addTask(300.3)
addTask(400.4)

schedule.start()

Copy the code

The execution result