Last active
April 28, 2021 04:32
-
-
Save jackyef/095f93ede2a6d14a4abfa59b73f902d0 to your computer and use it in GitHub Desktop.
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
const serialCon = (timeArray, maxConcurrency) => { | |
const startedPromises = [] | |
const times = [...timeArray] | |
const processNextPromise = () => { | |
const time = times.shift() | |
if (!time) return | |
const newPromise = new Promise((resolve) => | |
setTimeout(() => { | |
console.log(time) | |
resolve() | |
}, time) | |
) | |
const index = startedPromises.push(newPromise) - 1 | |
// Finished processed one promise | |
// Now we can process another one! | |
newPromise.then(() => { | |
startedPromises.splice(index, 1) | |
processNextPromise() | |
}) | |
// Maximum concurrency not reached yet, let's process another one | |
if (startedPromises.length < maxConcurrency) { | |
processNextPromise() | |
} | |
} | |
// Start the recursive calls off! | |
processNextPromise() | |
} | |
const timeoutArray = [1000, 100, 200, 300, 400, 500] | |
// serialCon(timeoutArray, 1) | |
serialCon(timeoutArray, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment