Last active
July 5, 2020 00:03
-
-
Save copperwall/c1a4e56e29c915067abd22c06ccfb17c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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