Promise Pool
Execute promises with controlled concurrency and result collection
Description
A pool for executing promises with controlled concurrency. Collects all results, handles errors, and provides progress tracking.
Features
- Concurrency control
- Result collection
- Error handling
- Progress tracking
Code
type Task<T> = () => Promise<T>;type ProgressCallback = (completed: number, total: number) => void;class PromisePool<T = any> { private concurrency: number; private tasks: Task<T>[]; private results: T[] = []; private errors: Error[] = []; constructor(concurrency: number = 3) { this.concurrency = concurrency; this.tasks = []; } add(task: Task<T>): this { this.tasks.push(task); return this; } async execute(onProgress?: ProgressCallback): Promise<{ results: T[]; errors: Error[] }> { this.results = []; this.errors = []; const executing: Promise<void>[] = []; let completed = 0; for (const task of this.tasks) { const promise = task() .then(result => { this.results.push(result); completed++; onProgress?.(completed, this.tasks.length); }) .catch(error => { this.errors.push(error instanceof Error ? error : new Error(String(error))); completed++; onProgress?.(completed, this.tasks.length); }) .finally(() => { executing.splice(executing.indexOf(promise), 1); }); executing.push(promise); if (executing.length >= this.concurrency) { await Promise.race(executing); } } await Promise.all(executing); return { results: this.results, errors: this.errors }; }}export default PromisePool;
import PromisePool from './PromisePool';const pool = new PromisePool(3);const urls = ["https://api.example.com/data1", "https://api.example.com/data2", "https://api.example.com/data3"];urls.forEach(url => { pool.add(() => fetch(url).then(r => r.json()));});const { results, errors } = await pool.execute((completed, total) => { console.log(`Progress: ${completed}/${total}`);});console.log(`Completed: ${results.length} successful, ${errors.length} errors`);
Comments
No comments yet. Be the first to comment!
Please login to leave a comment.