An asynchronous semaphore utility class meant to work with Deno. You can use it to implement rate-limiting and other concurrency patterns.
Usage example:
import { Semaphore } from "https://gist.githubusercontent.com/crabmusket/681b4f81ed05716f8dd10ac88d1d960b/raw/5e7c18013e896425d1048324f8668932f23437df/semaphore.ts";
const semaphore = new Semaphore(5);
semaphore.signal(3);
await semaphore.wait(1);
console.log('used 1, yay!');
if (semaphore.tryWait(3)) {
// this isn't reached, because there were only 2 left
}
If you don't want to limit the maximum capacity of your semaphore, just use new Semaphore(Infinity)
.
Note that the following operations constitute programmer error and will therefore throw exceptions:
- Attempting to
signal
orwait
for 0, a negative number,NaN
orInfinity
- Attempting to
signal
orwait
an amount greater than the Semaphore's capacity as passed in its constructor
To run tests:
deno https://gist.githubusercontent.com/crabmusket/681b4f81ed05716f8dd10ac88d1d960b/raw/5e7c18013e896425d1048324f8668932f23437df/semaphore_test.ts
https://github.com/notenoughneon/await-semaphore
- Doesn't allow acquiring more than 1 count of resource at a time
- Can only
release
resource from the closure thatacquire
d it (therefore I would argue it's not really a semaphore)
https://github.com/abrkn/semaphore.js
- Doesn't allow acquiring more than 1 count of resource at a time
- Not Deno-compatible