export class BatchedPromiseHandler { private batchSize: number; /** * max size 10 */ private currentBatch: Array<() => Promise> = []; private waitingBatch: Array<() => Promise> = []; constructor(batchSize: number = 10) { this.batchSize = batchSize; } private processPromises() { /** * while (this.currentBatch.length > 0) { * remove promise by shift * } * */ while (this.currentBatch.length > 0) { const promise = this.currentBatch.shift(); promise?.().then(() => { const waitingPromise = this.waitingBatch.shift(); if (waitingPromise) { this.currentBatch.push(waitingPromise); this.processPromises(); } }); } } add(promise: () => Promise) { if (this.currentBatch.length < this.batchSize) { this.currentBatch.push(promise); } else { this.waitingBatch.push(promise); } this.processPromises(); } clearPromises() { this.currentBatch = []; this.waitingBatch = []; } }