Created
November 1, 2016 12:05
-
-
Save branneman/78362b0e4799912600ff53adfc607bd6 to your computer and use it in GitHub Desktop.
executeBatched() – Run a list of async tasks as promises and wait after each batch
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
/** | |
* Run a list of async tasks as promises and wait after each batch | |
* @param {Number} batchSize - Number of tasks to run in parallel | |
* @param {Number} waitTime - Time to wait after each batch, in milliseconds | |
* @param {Array<Function>} tasks - Promise executor functions (not promise objects!) | |
* @return {Promise<Array<*>>} | |
*/ | |
function executeBatched(batchSize, waitTime, tasks) { | |
tasks = tasks.slice(); | |
const allResults = []; | |
return new Promise((resolve, reject) => { | |
const exec = function() { | |
const executors = tasks.slice(0, batchSize); | |
tasks = tasks.slice(batchSize); | |
Promise.all(executors.map(fn => new Promise(fn))) | |
.then(results => { | |
allResults.push.apply(allResults, results); | |
if (tasks.length) { | |
setTimeout(exec, waitTime); | |
} else { | |
resolve(allResults); | |
} | |
}) | |
.catch(reject); | |
}; | |
exec(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment