@esfx/async-semaphore
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

@esfx/async-semaphore

The @esfx/async-semaphore package provides the AsyncSemaphore class, an async coordination primitive.

Overview

Installation

npm i @esfx/async-semaphore

Usage

import { AsyncSemaphore } from "@esfx/async-semaphore";

// create a semaphore that allows one participant
const semaphore = new AsyncSemaphore(1);

async function updateResource(updates) {
    // Wait for a lock on the semaphore
    await semaphore.wait();
    try {
        // Between the 'wait' above and the 'release' below,
        // this function has exclusive access to a resource...

        // Await something async, allowing other logic to 
        // execute. If some other event/timer/etc. calls
        // 'updateResource' before this async operation
        // finishes, they will be blocked at the 'wait' above.
        await doSomethingAsync();

        // We still have exclusive access even after resuming,
        // so we can continue to use our exclusive access.
    }
    finally {
        // Release the semaphore. The next waiter will
        // be unblocked and will have the lock instead.
        semaphore.release();
    }
}

API

You can read more about the API here.

Readme

Keywords

none

Package Sidebar

Install

npm i @esfx/async-semaphore

Weekly Downloads

154

Version

1.0.0

License

Apache-2.0

Unpacked Size

39.6 kB

Total Files

9

Last publish

Collaborators

  • rbuckton