Async Semaphore For Concurrency Limit
Limit concurrent access to a resource with an async semaphore supporting acquire release and run helpers.
Code
export function asyncSemaphore(max){let current=0;const waiters=[];async function acquire(){if(current<max){current++;return;}return new Promise(r=>waiters.push(r));}function release(){if(waiters.length>0){const next=waiters.shift();next();}else current--;}async function run(fn){await acquire();try{return await fn();}finally{release();}}return{acquire,release,run,available:()=>max-current};}Report a problem with this exampleOpens a pre-filled issue on GitHub.