Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

await-semaphore

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

await-semaphore

Awaitable semaphore/mutex

  • 0.1.3
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

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 style

Also includes Mutex as a convenience for new Semaphore(1).

API

new Semaphore(count: number)

Create a new semaphore with the given count.

import {Semaphore} from 'await-semaphore';

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.

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.

semaphore.use(() => {
    //critical section...
});

new Mutex()

An alias for new Semaphore(1). Mutex has the same methods as Semaphore.

import {Mutex} from 'await-semaphore';

var mutex = new Mutex();

Examples

Create a version of fetch() with concurrency limited to 10.

async/await style (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)

var semaphore = new Semaphore(10);

function niceFetch(url) {
    return semaphore.use(() => fetch(url));
}

promise style (javascript)

var semaphore = new Semaphore(10);

function niceFetch(url) {
    return semaphore.acquire()
    .then(release => {
        return fetch(url)
        .then(result => {
            release();
            return result;
        });
    });
}

Keywords

FAQs

Package last updated on 27 Sep 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc