Skip to content

Instantly share code, notes, and snippets.

@cqsd
Created July 2, 2020 04:11
Show Gist options
  • Save cqsd/c55595b4c21488fa8389f45605db5fa7 to your computer and use it in GitHub Desktop.
Save cqsd/c55595b4c21488fa8389f45605db5fa7 to your computer and use it in GitHub Desktop.
basically a closure-based semaphore
/**
* Limit concurrent asynchronous execution of a function.
*
* Stolen from this:
* https://dev.to/ycmjason/limit-concurrent-asynchronous-calls-5bae
*
* @param fn {Function} async function
* @paranm n {Number} max execution concurrency
*/
const asyncLimit = (fn, n) => {
const pending = new Set();
return async (...args) => {
while (pending.size >= n) {
await Promise.race(pending);
}
const p = fn(...args);
const r = p
.catch(() => {})
.finally(() => pending.delete(r)); // lit
pending.add(r);
return p;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment