Skip to content

Instantly share code, notes, and snippets.

@antlis
Created April 16, 2026 20:08
Show Gist options
  • Select an option

  • Save antlis/3a164eae803dd78ba3c440d9ac68f4d0 to your computer and use it in GitHub Desktop.

Select an option

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.
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();
});
}
@antlis
Copy link
Copy Markdown
Author

antlis commented Apr 16, 2026

Use case:

const limit = pLimit(3);

await Promise.all(
  urls.map(url => limit(() => fetch(url)))
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment