js

实现代码

class Schedule {
  private queue: (() => Promise<any>)[] = [];
  private runningTasks: number = 0;
  private maxConcurrentTasks: number = 2;
  
  addTasks<T>(task: () => Promise<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      this.queue.push(() => task().then(resolve).catch(reject));
      this.runNext();
    });
  }
  
  private runNext() {
    if (this.runningTasks < this.maxConcurrentTasks && this.queue.length > 0) {
      const task = this.queue.shift();
      if (task) {
        this.runningTasks++;
        task()
          .then(() => {
            this.runningTasks--;
            this.runNext();
          })
          .catch(() => {
            this.runningTasks--;
            this.runNext();
          });
      }
    }
  }
}
  
const schedule = new Schedule();
  
function sleep(ms: number): Promise<number> {
  return new Promise((resolve) => setTimeout(() => resolve(ms), ms));
}
  
schedule.addTasks(() => sleep(1000)).then((data) => console.log(1, data));
schedule.addTasks(() => sleep(500)).then((data) => console.log(2, data));
schedule.addTasks(() => sleep(300)).then((data) => console.log(3, data));
schedule.addTasks(() => sleep(400)).then((data) => console.log(4, data));
//输出 2 3 1 4