Created
June 18, 2021 21:14
-
-
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.
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
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