Created
February 22, 2020 13:14
-
-
Save Ovyerus/4105205a8eb114537aae68f0ed2b0068 to your computer and use it in GitHub Desktop.
Serially execute a chunk of parallel tasks one after another (without caring about return value)
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 chunk = (arr, n) => | |
Array.from({ length: Math.ceil(arr.length / n) }, (v, i) => | |
// eslint-disable-next-line no-mixed-operators | |
arr.slice(i * n, i * n + n) | |
); | |
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
chunk(data, 2) | |
// Turn each chunk into a function that will await all of its parts to resolve before finishing | |
.map(chunk => () => Promise.all(chunk.map(part => Promise.resolve(part)))) | |
// Execute each chunk serially (hopefully) by chaining it to the previous one | |
// Note: doesn't persist previous return value by the end. Could be done but I'm lazy. | |
.reduce((chain, current) => chain.then(current), Promise.resolve()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment