2. class Scheduler {
constructor(parallelCount = 2) {
this.parallelCount = parallelCount;
this.runningCount = 0;
this.task = [];
}
add(task) {
return new Promise((resolve, reject) => {
this.task.push({
task,
resolve,
reject,
});
this._run();
});
}
_run() {
if (this.task.length > 0 && this.runningCount < this.parallelCount) {
const { task, resolve, reject } = this.task.shift();
this.runningCount++;
task()
.then(resolve, reject)
.finally(() => {
this.runningCount--;
this._run();
});
}
}
}