Created
June 28, 2022 12:15
-
-
Save zdila/dc0cdb68657efc22627414e0fb6fb600 to your computer and use it in GitHub Desktop.
pLimit for modern Node
This file contains 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: number) { | |
let running = 0; | |
let resolves: (() => void)[] = []; | |
return async <T>(fn: () => Promise<T>): Promise<T> => { | |
if (running >= concurrency) { | |
await new Promise<void>((resolve) => { | |
resolves.push(resolve); | |
}); | |
} | |
running++; | |
return (async () => { | |
try { | |
return await fn(); | |
} finally { | |
running--; | |
resolves[0]?.(); | |
resolves.shift(); | |
} | |
})(); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment