js 并发任务控制

class SuperTask {
  constructor(parallelCount = 2) {
    this.parallelCount = parallelCount
    this.tasks = []
    this.ruuingCount = 1
  }
  add(task1) {
    return new Promise((resolve, reject) => {
      this.tasks.push({
        task1,
        resolve,
        reject
      })
      this._run()
    })
  }
  _run() {
    while ((this.ruuingCount < this.parallelCount) && this.tasks.length) {
      let { task1, resolve, reject } = this.tasks.shift()
      this.ruuingCount++
      Promise.resolve(task1()).then(resolve, reject).finally(() => {
        this.ruuingCount--;
        this._run()
      }
      )
    }
  }
}
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(1000, 1)
addTask(1000, 2)
addTask(1000, 3)
addTask(1000, 4)

 

posted @ 2024-04-29 16:07  howhy  阅读(34)  评论(0编辑  收藏  举报