Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active January 15, 2019 09:51
Show Gist options
  • Save ccnokes/34b99df44f2773bd25dcb05f21badd7a to your computer and use it in GitHub Desktop.
Save ccnokes/34b99df44f2773bd25dcb05f21badd7a to your computer and use it in GitHub Desktop.
Chunk async tasks into batches and process in parallel
// dummy async task
function asyncTask(n) {
return new Promise(resolve => setTimeout(() => resolve(n), 500));
}
// takes a flat array and returns a nested one, eg. chunkArray([1,2,3], 1) ==> [[1],[2],[3]]
function chunkArray(arr, chunkSize) {
return arr.reduce((aggr, item) => {
let lastArr = aggr[aggr.length - 1];
if (lastArr.length < chunkSize) {
lastArr.push(item);
} else {
aggr.push([item]);
}
return aggr;
}, [[]])
}
async function runTasks(arr, concurrency) {
// chunks it into "jobs"
let chunks = chunkArray(arr, concurrency);
// process chunks in parallel, proceed to next when done
for (let chunk of chunks) {
let taskPromises = chunk.map(n => asyncTask(n).then(console.log));
// when this is complete, it'll proceed to the next chunk
await Promise.all(taskPromises);
}
}
runTasks([1,2,3,4,5,6,7,8,10], 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment