Skip to content

Instantly share code, notes, and snippets.

@copperwall
Last active July 5, 2020 00:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save copperwall/c1a4e56e29c915067abd22c06ccfb17c to your computer and use it in GitHub Desktop.
Save copperwall/c1a4e56e29c915067abd22c06ccfb17c to your computer and use it in GitHub Desktop.
type PromiseFactory = () => Promise<any>;
function promiseAllBatched(
promiseFactories: PromiseFactory[],
batchSize: number
): Promise<any> {
let completed = 0;
let upNext = 0;
let results: any[] = [];
const initialBatchSize = Math.min(batchSize, promiseFactories.length);
return new Promise((resolve, reject) => {
function onPromiseCompletion(index: number, result: any): void {
completed += 1;
results[index] = result;
if (completed == promiseFactories.length) {
// Done Case
resolve(results);
return;
}
if (upNext < promiseFactories.length) {
promiseFactories[upNext]().then(
onPromiseCompletion.bind(null, upNext),
onPromiseCompletion.bind(null, upNext)
);
upNext += 1;
}
}
if (batchSize <= 0 || typeof batchSize !== "number") {
reject(new Error("Invalid batch size, please supply a positive number"));
} else {
for (let i = 0; i < initialBatchSize; i++) {
promiseFactories[i]().then(
onPromiseCompletion.bind(null, i),
onPromiseCompletion.bind(null, i)
);
}
upNext = initialBatchSize;
}
});
}
function waitRandomTimeSecondsReturnFive(): Promise<number> {
return new Promise((resolve) => {
setTimeout(() => resolve(5), 1000 + Math.floor(Math.random() * 1000));
});
}
promiseAllBatched(Array(1000).fill(waitRandomTimeSecondsReturnFive), 100).then(
console.log
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment