Last active
August 5, 2019 11:40
-
-
Save andrIvash/db17bfb792c9af5820c51394f6803f2a to your computer and use it in GitHub Desktop.
Limit number of promises running in parallel
This file contains hidden or 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
// 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