-
Notifications
You must be signed in to change notification settings - Fork 470
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add chunked-parallel from events page branch
- Loading branch information
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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(); | ||
}); | ||
}; |