typescriptadvanced
Promise Queue with Concurrency Limit
A queue that processes async tasks with a configurable concurrency limit to prevent resource exhaustion.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptadvanced
Node.js In-Memory Task Queue
A simple in-memory task queue with concurrency control, retries, and priority support.
Best for: Rate-limited API call processing
#nodejs#queue
typescriptintermediate
Promise Concurrency Patterns
Master Promise.all, allSettled, race, any — parallel execution with error handling and timeouts.
Best for: Parallel API calls with error handling
#nodejs#promise
typescriptintermediate
Semaphore for Concurrency Limiting
Control concurrent async operations with a semaphore pattern: rate limiting, connection pooling, and batch processing.
Best for: API rate limiting
#nodejs#concurrency
pythonintermediate
asyncio.gather Concurrent Tasks
Run multiple async operations concurrently with asyncio.gather and proper error handling.
Best for: Parallel API calls
#asyncio#concurrency