Skip to content

Instantly share code, notes, and snippets.

@dawaltconley
Created June 18, 2021 21:14
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 dawaltconley/b28c86ee35de33d6635f559f7d647202 to your computer and use it in GitHub Desktop.
Save dawaltconley/b28c86ee35de33d6635f559f7d647202 to your computer and use it in GitHub Desktop.
A simple module for executing some maximum number of async functions in parallel.
module.exports = async (tasks, n) => {
const results = new Array(tasks.length);
const executing = [];
let index = 0;
while (index < tasks.length || executing.length) {
if (index < tasks.length && executing.length < n) {
let task = tasks[index];
let taskIndex = index;
task = task().then(r => {
const i = executing.indexOf(task);
executing.splice(i, 1);
results[taskIndex] = r;
});
executing.push(task);
index++;
} else {
await Promise.race(executing);
}
}
return results;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment