Last active
April 30, 2021 23:56
-
-
Save HichamBenjelloun/1f8902db442195d33156576a4e86e1b1 to your computer and use it in GitHub Desktop.
Limiting the number of concurrent running promises
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
let runningPromiseCount = 0; | |
const examplePromiseRunnerQueue = new Array(10) | |
.fill(0) | |
.map((_, idx) => idx) | |
.map((idx) => { | |
return async () => { | |
console.log( | |
`[${new Date().toISOString()}] Promise ${idx} will run! \n# of running promises: ${runningPromiseCount}` | |
); | |
runningPromiseCount++; | |
return await new Promise((resolve) => { | |
setTimeout(() => { | |
resolve(idx); | |
runningPromiseCount--; | |
}, idx * 1000); | |
}); | |
}; | |
}); | |
const run = (promiseRunnerQueue = [], max = promiseRunnerQueue.length) => { | |
const executeAndDelegateNextCall = async (promiseRunner) => { | |
try { | |
await promiseRunner(); | |
} finally { | |
if (promiseRunnerQueue.length === 0) { | |
return; | |
} | |
const nextPromiseRunner = promiseRunnerQueue.shift(); | |
executeAndDelegateNextCall(nextPromiseRunner); | |
} | |
}; | |
promiseRunnerQueue.splice(0, max).forEach(executeAndDelegateNextCall); | |
}; | |
run(examplePromiseRunnerQueue, 10); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example trace output: