Async Semaphore Concurrency Limit
Cap concurrent async tasks with a promise-based semaphore that queues waiters and releases permits safely.
Code
export class Semaphore {
constructor(limit) {
if (!Number.isInteger(limit) || limit <= 0) throw new RangeError('limit must be a positive integer');
this.limit = limit;
this.active = 0;
this.waiters = [];
}
async acquire() {
if (this.active < this.limit) {
this.active += 1;
return () => this.release();
}
await new Promise((resolve) => this.waiters.push(resolve));
this.active += 1;
return () => this.release();
}
release() {
if (this.active === 0) throw new Error('release without acquire');
this.active -= 1;
const next = this.waiters.shift();
if (next) {
this.active += 1;
next(() => this.release());
}
}
async run(task) {
const release = await this.acquire();
try {
return await task();
} finally {
release();
}
}
}How the snippet works
The working surface is the class Semaphore — everything else is wiring.
await marks each async boundary — nothing fires and forgets. Invalid states are rejected up front: it throws RangeError and Error instead of continuing with bad data.
Points of care
- The guard
this.active === 0short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
Import Semaphore from the file and call it — the rest of the code is implementation detail.
Statements that matter
await new Promise((resolve) => this.waiters.push(resolve));
return () => this.release();
return await task();
Interactive Tools for This Topic
FAQ
- How are precondition violations signaled?
- It throws `RangeError` and `Error` before any real work runs, via the guard `this.active === 0` — handle it at the call site or let it propagate deliberately.
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement.
Report a problem with this exampleOpens a pre-filled issue on GitHub.