Skip to content

Commit

Permalink
add chunked-parallel from events page branch
Browse files Browse the repository at this point in the history
  • Loading branch information
olaszakos committed Jan 16, 2024
1 parent e64f5de commit e856ef4
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions plugins/utils/chunked-parallel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* Run tasks in parallel, but limit the number of tasks running at the same time.
* @param {Array} tasks - Array of functions that return promises.
* @param {Number} chunkSize - Number of tasks to run in parallel.
* @returns {Array} - Array of results.
*/
module.exports = function chunkedParallel(tasks, chunkSize) {
return new Promise((resolve, reject) => {
const results = [];
let index = 0;

function runNext() {
if (index >= tasks.length) {
return resolve(results);
}

const chunk = tasks.slice(index, index + chunkSize);
index += chunkSize;

Promise.all(chunk.map((task) => task()))
.then((chunkResults) => {
results.push(...chunkResults);
runNext();
})
.catch(reject);
}

runNext();
});
};

0 comments on commit e856ef4

Please sign in to comment.