并行排除任务代码

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._runTask()
        })
      };
      _runTask() {
        while (this.runningCount < this.parallelCount && this.tasks.length) {
          const { task, resolve, reject } = this.tasks.pop();
          this.runningCount++;
          Promise.resolve(task()).then(resolve, reject).finally(() => {
            this.runningCount--;
            this._runTask()
          })
        }
      }
    }
    function timeout(time) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve()
        }, time);
      })
    }
    const superTask = new SuperTask()
    function addTask(time, name) {
      superTask.add(() => timeout(time)).then(() => console.log(`task ${name} finish`))
    }
    // addTask(10000, 1)
    // addTask(2000, 2)
    // addTask(3000, 3)
    // addTask(4000, 4)
posted @ 2024-05-16 17:34  howhy  阅读(2)  评论(0编辑  收藏  举报