Skip to content

Instantly share code, notes, and snippets.

@branneman
Created November 1, 2016 12:05
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 branneman/78362b0e4799912600ff53adfc607bd6 to your computer and use it in GitHub Desktop.
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
/**
* 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