控制并发, 实现 SuperTask
js
function timeout(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
const superTask = new SuperTask();
function addTask(time, name) {
superTask
.add(() => timeout(time))
.then(() => {
console.log(`${name} 执行完毕`);
});
}
addTask(10000, "task1"); // 10000ms后 task1 执行完毕
addTask(5000, "task2"); // 5000ms后 task2 执行完毕
addTask(3000, "task3"); // 8000ms后 task3 执行完毕
addTask(4000, "task4"); // 12000ms后 task4 执行完毕
addTask(5000, "task5"); // 15000ms后 task5 执行完毕
js
class SuperTask {
constructor(maxCount = 2) {
this.maxCount = maxCount;
this.tasks = [];
this.penddingCount = 0;
}
add(task) {
return new Promise((resolve, reject) => {
this.tasks.push({
task,
resolve,
reject,
});
this._run();
});
}
_run() {
while (this.penddingCount < this.maxCount && this.tasks.length) {
const { task, resolve, reject } = this.tasks.shift();
this.penddingCount++;
task()
.then(resolve, reject)
.finally(() => {
this.penddingCount--;
this._run();
});
}
}
}