Skip to content

Instantly share code, notes, and snippets.

@Xetera
Created February 17, 2019 11:13
Show Gist options
  • Save Xetera/f384978991364ca08d71ccdb7c7e1dc1 to your computer and use it in GitHub Desktop.
Save Xetera/f384978991364ca08d71ccdb7c7e1dc1 to your computer and use it in GitHub Desktop.
Mapping an array asynchronously with maximum N number of concurrent requests
const parallelMap = (arr, fn, max) => {
const out = [];
const initial = [...Array(max)];
const fired = initial.map(() => Promise.resolve().then(async function cb() {
if (!arr.length) return
const next = arr.shift();
out.push(await fn(next));
return cb();
}));
return Promise.all(fired).then(() => out);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment