@weegigs/concurrent
v1.2.0
Published
Concurrency utilities for Typescript
Downloads
4
Maintainers
Readme
@weegigs/concurrent
Utilities for dealing with concurrency in Typescript (and Javascript).
Overview
Concurrent provides two handy classes when you want to limit the amount of concurrent work being executed in
Promise
s, Semaphore
and Mutex
.
Semaphore
and Mutex
share a common interface Gate
. The Gate
interface provides two functions acquire
and execute
.
acquire(timeout?: number): Promise<Release>
If a timeout greater than zero is passed then a TimeoutError
will be triggered if the duration in milliseconds
is exceeded.
try {
const release = await gate.acquire(10);
// ... do some work ...
release();
} catch (error) {
release();
}
execute<T>(worker: Worker<T>, timeout?: number): Promise<T>;
execute
allows you to avoid managing the Release
function by using a Worker
. A Worker
is a function from
void
to T
or Promise<T>
.
As with acquire
, if a timeout greater than zero is passed then a TimeoutError
will be triggered if the
duration in milliseconds is exceeded.
try {
const result = await gate.execute(() => {
// ... do some work ...
return value;
}, 10);
// ...do something with the value...
} catch (error) {
// ... do something with the error ...
}
Todo
- [x] Semaphore
- [x] Mutex
- [x] Latch
- [ ] Example Usage
- [ ] Documentation