Skip to content

Instantly share code, notes, and snippets.

@batrudinych
Created January 14, 2019 10:19
Show Gist options
  • Save batrudinych/440842b71873d9cde17ae291d683127e to your computer and use it in GitHub Desktop.
Save batrudinych/440842b71873d9cde17ae291d683127e to your computer and use it in GitHub Desktop.
Run promises in parallel, applying the concurrency limit
**
* Run Promises in parallel with a concurrency limit
* @param args - List of arguments to be passed to 'fn'
* @param fn - A function to apply to each argument. MUST return a Promise
* @param concurrency - Allowed amount of Promises to be run in parallel
* @returns {Promise} - A Promise, which eventually resolved with a list of results.
* Order corresponds to the list of arguments.
*/
function mapPromises(args, fn, concurrency = 1) {
if (!args.length) return Promise.resolve([]);
const argsCopy = [].concat(args.map((val, ind) => ({ val, ind })));
const result = new Array(args.length);
const promises = new Array(concurrency).fill(Promise.resolve());
function chainNext(p) {
if (argsCopy.length) {
const arg = argsCopy.shift();
return p.then(() => {
const operationPromise = fn(arg.val).then(r => { result[arg.ind] = r; });
return chainNext(operationPromise);
});
}
return p;
}
return Promise.all(promises.map(chainNext)).then(() => result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment