Skip to content

Instantly share code, notes, and snippets.

@zdila
Created June 28, 2022 12:15
Show Gist options
  • Save zdila/dc0cdb68657efc22627414e0fb6fb600 to your computer and use it in GitHub Desktop.
Save zdila/dc0cdb68657efc22627414e0fb6fb600 to your computer and use it in GitHub Desktop.
pLimit for modern Node
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