Skip to content

Instantly share code, notes, and snippets.

@Ovyerus
Created February 22, 2020 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ovyerus/4105205a8eb114537aae68f0ed2b0068 to your computer and use it in GitHub Desktop.
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)
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