Skip to content

Instantly share code, notes, and snippets.

@andrIvash
Last active August 5, 2019 11:40
Show Gist options
  • Save andrIvash/db17bfb792c9af5820c51394f6803f2a to your computer and use it in GitHub Desktop.
Save andrIvash/db17bfb792c9af5820c51394f6803f2a to your computer and use it in GitHub Desktop.
Limit number of promises running in parallel
// example lib https://github.com/charto/cwait
// https://krasimirtsonev.com/blog/article/implementing-an-async-queue-in-23-lines-of-code
function createQueue(tasks, maxNumOfWorkers = 4) {
let numOfWorkers = 0;
let taskIndex = 0;
const resultData = [];
return new Promise(done => {
const handleResult = index => result => {
resultData[index] = result;
numOfWorkers--;
getNextTask();
};
const getNextTask = () => {
if (numOfWorkers < maxNumOfWorkers && taskIndex < tasks.length) {
tasks[taskIndex]()
.then(handleResult(taskIndex))
.catch(handleResult(taskIndex));
taskIndex++;
numOfWorkers++;
getNextTask();
} else if (numOfWorkers === 0 && taskIndex === tasks.length) {
done(resultData);
}
};
getNextTask();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment