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)
标签:addTask,resolve,tasks,代码,并行,排除,task,reject,runningCount From: https://www.cnblogs.com/howhy/p/18196378