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};}Inside the snippet
The working surface is the functions asyncSemaphore, acquire, release and run — everything else is wiring.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
The result comes back as an object carrying acquire, release, run.
Using it
The main signature reads export function asyncSemaphore(max)
Treat asyncSemaphore as the API: import it, and ignore the supporting code.
The call returns acquire, release, run — destructure what you need at the call site.
Interactive Tools for This Topic
FAQ
- Does `asyncSemaphore` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. The file defines `asyncSemaphore`, `acquire`, `release` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.