Created
April 16, 2026 20:08
-
-
Save antlis/3a164eae803dd78ba3c440d9ac68f4d0 to your computer and use it in GitHub Desktop.
Limits the number of concurrently running async operations. Useful for rate-limited APIs or controlling resource usage.
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
| export function pLimit(concurrency) { | |
| const queue = []; | |
| let activeCount = 0; | |
| const next = () => { | |
| if (queue.length === 0 || activeCount >= concurrency) return; | |
| activeCount++; | |
| const { fn, resolve, reject } = queue.shift(); | |
| fn() | |
| .then(resolve, reject) | |
| .finally(() => { | |
| activeCount--; | |
| next(); | |
| }); | |
| }; | |
| return (fn) => | |
| new Promise((resolve, reject) => { | |
| queue.push({ fn, resolve, reject }); | |
| next(); | |
| }); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use case: