class Scheduler {
constructor(maxConcurrent) {
this.maxConcurrent = maxConcurrent;
this.queue = [];
this.currentCount = 0;
}
add(promise) {
return new Promise((resolve, reject) => {
this.queue.push(() => promise().then(resolve).catch(reject));
this.run();
});
}
run() {
if (this.currentCount < this.maxConcurrent) {
const task = this.queue.shift();
if (task) {
this.currentCount++;
task().finally(() => {
this.currentCount--;
this.run();
});
}
}
}
}
// Example usage:
const scheduler = new Scheduler(2);
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function task(id) {
console.log(`Task ${id} started`);
return delay(1000).then(() => {
console.log(`Task ${id} completed`);
});
}
for (let i = 0; i < 5; i++) {
scheduler.add(() => task(i));
}
具体的实现思路如下:
- 定义一个
Scheduler类来实现 Promise 调度器。 Scheduler类的构造函数接受一个参数maxConcurrent,用来限制并行执行的 Promise 数量。- 在
Scheduler类中定义一个队列queue,用来保存待执行的 Promise。 - 在
Scheduler类中定义一个变量currentCount,用来记录当前正在执行的 Promise 数量。 Scheduler类中定义一个add方法,该方法接受一个 Promise 生成器函数promise,返回一个新的 Promise。- 在
add方法中,首先将promise生成器函数封装成一个新的 Promise,然后将其添加到队列queue中。 - 在
add方法中,调用run方法来执行队列中的 Promise。 Scheduler类中定义一个run方法,用来执行队列中的 Promise。- 在
run方法中,首先检查当前正在执行的 Promise 数量是否小于并行限制数maxConcurrent,如果小于,则从队列queue中取出一个 Promise 并执行。 - 在
run方法中,每当一个 Promise 完成执行后,将currentCount减 1,并再次执行run方法,以便执行队列中的下一个 Promise。 - 在
run方法中,每当一个 Promise 开始执行时,将currentCount加 1。
这种实现方式使用了队列来限制并行执行的 Promise 数量,通过一个队列来保存待执行的 Promise,然后通过递归执行队列中的 Promise 来实现并行限制的效果。这样就可以确保同时最多只有 maxConcurrent 个 Promise 在执行,从而避免了因过多的并行执行而导致的性能问题。