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

  class SuperTask {
    constructor(parallelCount = 2) {
      this.parallelCount = parallelCount;
      this.tasks = [];
      this.runningCount = 0;
    }

    add(task) {
      return new Promise((resolve, reject) => {
        this.tasks.push({
          task,
          resolve,
          reject
        });
        this._run();
      })
    }

    _run() {
      while (this.runningCount < this.parallelCount && this.tasks.length > 0) {
        const {task, resolve, reject} = this.tasks.shift();
        this.runningCount++;
        task().then(resolve, reject).finally(() => {
          this.runningCount--;
          this._run();
        });
      }
    }
  }

  const superTask = new SuperTask();

  function addTask(time, name) {
    superTask
     .add(() => timeout(time))
     .then(() => {
       console.log(`任务${name}已完成`);
     })
  }

  addTask(10000, 1);  //10000ms后输出:任务1已完成
  addTask(5000, 2);  //5000ms后输出:任务2已完成
  addTask(3000, 3);  //8000ms后输出:任务3已完成
  addTask(4000, 4); //12000ms后输出:任务4已完成
  addTask(5000, 2); //15000ms后述出:任务5已完成
Last modification:February 17, 2024
如果觉得我的文章对你有用,请随意赞赏