Last active
September 14, 2018 12:45
-
-
Save lupomontero/e43cff8884946e510b4285fab99a5ed7 to your computer and use it in GitHub Desktop.
Process promise-based tasks in batches
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
const splitArrayIntoBatches = (arr, limit) => arr.reduce((memo, item) => { | |
if (memo.length && memo[memo.length - 1].length < limit) { | |
memo[memo.length - 1].push(item); | |
return memo; | |
} | |
return [...memo, [item]]; | |
}, []); | |
const batched = (tasks, concurrency) => { | |
const processBatches = (batches, prevResults = []) => ( | |
(!batches.length) | |
? Promise.resolve(prevResults) | |
: Promise.all(batches[0].map(fn => fn())) | |
.then(batchResults => processBatches(batches.slice(1), [ | |
...prevResults, | |
...batchResults, | |
])) | |
); | |
return processBatches(splitArrayIntoBatches(tasks, concurrency)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment