Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/jd1378/deno-semaphore
https://deno.land/x/[email protected]
https://github.com/jd1378/deno-semaphore
Last synced: 13 days ago
JSON representation
https://deno.land/x/[email protected]
- Host: GitHub
- URL: https://github.com/jd1378/deno-semaphore
- Owner: jd1378
- License: mit
- Created: 2021-01-25T04:23:13.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2022-10-20T15:28:29.000Z (about 2 years ago)
- Last Synced: 2024-09-17T16:10:50.579Z (about 2 months ago)
- Language: TypeScript
- Homepage:
- Size: 12.7 KB
- Stars: 6
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# deno-semaphore
This is a quick port of [await-semaphore](https://www.npmjs.com/package/await-semaphore)
The use case should be identical.
I'll include It's readme here for ease of access:
## await-semaphore
Awaitable semaphore/mutex
A semaphore implementation using ES6 promises and supporting 3 styles:
* async/await style (needs typescript)
* thunk style (automatic acquire/release)
* promise styleAlso includes `Mutex` as a convenience for `new Semaphore(1)`.
## API
### new Semaphore(count: number)
Create a new semaphore with the given count.
```javascript
import {Semaphore} from '...';var semaphore = new Semaphore(10);
```### semaphore.acquire(): Promise<() => void>
Acquire the semaphore and returns a promise for the release function. Be sure to handle release for exception case.
```javascript
semaphore.acquire()
.then(release => {
//critical section...
doSomething()
.then(res => {
//...
release();
})
.catch(err => {
//...
release();
});
});
```### semaphore.use(thunk: () => Promise): Promise
Alternate method for using the semaphore by providing a thunk. This automatically handles acquire/release.
```javascript
semaphore.use(() => {
//critical section...
});
```### new Mutex()
An alias for `new Semaphore(1)`. Mutex has the same methods as Semaphore.
```javascript
import {Mutex} from 'await-semaphore';var mutex = new Mutex();
```## Examples
Create a version of `fetch()` with concurrency limited to 10.
### async/await style (typescript)
```typescript
var semaphore = new Semaphore(10);async function niceFetch(url) {
var release = await semaphore.acquire();
var result = await fetch(url);
release();
return result;
}
```### thunk style (javascript)
```javascript
var semaphore = new Semaphore(10);function niceFetch(url) {
return semaphore.use(() => fetch(url));
}
```### promise style (javascript)
```javascript
var semaphore = new Semaphore(10);function niceFetch(url) {
return semaphore.acquire()
.then(release => {
return fetch(url)
.then(result => {
release();
return result;
});
});
}
```