src/queue.ts740 B · typescript
export class AsyncQueue {
private queue: (() => Promise<void>)[] = [];
private activeCount = 0;
constructor(private concurrency: number) {}
async add<T>(task: () => Promise<T>): Promise<T> {
return new Promise<T>((resolve, reject) => {
this.queue.push(async () => {
try {
resolve(await task());
} catch (e) {
reject(e);
}
});
this.process();
});
}
private async process() {
if (this.activeCount >= this.concurrency || this.queue.length === 0) return;
this.activeCount++;
const task = this.queue.shift();
if (task) {
try {
await task();
} finally {
this.activeCount--;
this.process();
}
}
}
}