typescriptadvanced

Promise Queue with Concurrency Limit

A queue that processes async tasks with a configurable concurrency limit to prevent resource exhaustion.

typescript
class PromiseQueue {
  private running = 0;
  private queue: (() => Promise<void>)[] = [];

  constructor(private readonly concurrency: number) {}

  async add<T>(fn: () => Promise<T>): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      const run = async () => {
        this.running++;
        try {
          const result = await fn();
          resolve(result);
        } catch (err) {
          reject(err);
        } finally {
          this.running--;
          this.next();
        }
      };

      if (this.running < this.concurrency) {
        run();
      } else {
        this.queue.push(run);
      }
    });
  }

  private next() {
    if (this.queue.length > 0 && this.running < this.concurrency) {
      const fn = this.queue.shift()!;
      fn();
    }
  }
}

// Usage:
// const queue = new PromiseQueue(3);
// await Promise.all(urls.map(url => queue.add(() => fetch(url))));

Use Cases

  • Rate-limited API calls
  • Batch file processing

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.