Last active
March 6, 2020 15:40
-
-
Save khaledosman/cda5f8a9a69f256fa9dc70a3cf0bb5ed to your computer and use it in GitHub Desktop.
chunked / batched promise execution
This file contains hidden or 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
| export function runInSeries (funcs: Array<() => Promise<any>>): Promise<any> { | |
| const results = [] | |
| return funcs.reduce((accumulator, f) => accumulator.then(async () => { | |
| const result = await f() | |
| results.push(result) | |
| return results | |
| }), Promise.resolve()) | |
| } | |
| export function runInParallel (funcs: Array<() => Promise<any>>): Promise<any[]> { | |
| return Promise.all(funcs.map(f => f())) | |
| } | |
| export function createBatchRequestsFromItems (funcs: Array<() => Promise<any>>, batchSize = 25): Array<() => Promise<any>> { | |
| const promiseArr = [] | |
| for (let i = 0; i < funcs.length; i += batchSize) { | |
| const batch = funcs.slice(i, i + batchSize) | |
| promiseArr.push(() => runInParallel(batch)) | |
| } | |
| return promiseArr | |
| } | |
| export function runInBatches (funcs: Array<() => Promise<any>>, batchSize): Promise<any> { | |
| return runInSeries(createBatchRequestsFromItems(funcs, batchSize)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment