限制数量的并发任务
ts
interface Task {
task: unknown;
res: (value: unknown) => void;
rej: (reason?: any) => void;
}
class SuperTask {
private max: number;
private current: number = 0;
waiting: Task[];
constructor(max = 2) {
this.waiting = [];
this.max = max;
}
add(task: unknown): Promise<unknown> {
return new Promise<unknown>((res, rej) => {
this.waiting.push({ task, res, rej });
this.run();
});
}
private run() {
if (this.waiting.length === 0) return;
if (this.current >= this.max) return;
const waitingTask = this.waiting.shift();
if (!waitingTask) return;
const { task, res, rej } = waitingTask;
this.current++;
if (typeof task === 'function') {
Promise.resolve(task())
.then(res, rej)
.finally(() => {
this.current--;
this.run();
});
} else {
Promise.resolve(task)
.then(res, rej)
.finally(() => {
this.current--;
this.run();
});
}
}
}
const superTask = new SuperTask(2);
function timeout(time: number) {
return new Promise((res) => {
setTimeout(res, time);
});
}
function addTask(time: number, name: string) {
superTask
.add(() => timeout(time))
.then(() => {
console.log(`${name} finished`);
console.timeLog('task');
});
}
console.time('task');
addTask(10000, 'task1');
addTask(5000, 'task2');
addTask(3000, 'task3');
addTask(4000, 'task4');
addTask(5000, 'task5');