Skip to content

js控制函数的并发数量

js
class SuperTask {
      constructor(paralleCount = 2) {
        this.paralleCount = paralleCount
        this.taskList = []
        this.currentCount = 0
      }

      add (task) {
        return new Promise((resolve, reject) => {
          this.taskList.push({
            task,
            resolve,
            reject
          })
          this.run()
        })
      }

      run () {
        while (this.currentCount < this.paralleCount && this.taskList.length > 0) {
          const taskItem = this.taskList.shift()
          this.currentCount++
          taskItem.task()
            .then(taskItem.resolve)
            .catch(taskItem.reject)
            .finally(() => {
              this.currentCount--
              this.run()
            })
        }
      }
    }


    async function invokeFun () {
      const sTask = new SuperTask(2)
      const pArr = []
      for (let i = 0; i < 100; i++) {
        sTask.add(() => {
          return new Promise((resolve, reject) => {
            setTimeout(() => {
              resolve(i)
            }, 1000)
          })
        }).then(() => {
          console.log(`第${i}个成功`)
        }).catch((err) => {
          console.log(`第${i}个失败:${err}`)
        })
      }
    }
    invokeFun()

备案号:豫ICP备17017964号