1.0.0 • Published 9 months ago

@giancosta86/sync-tools v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

sync-tools

Synchronization tools for TypeScript

GitHub CI npm version MIT License

Introduction

sync-tools is a TypeScript library providing functional-style synchronization tools.

Installation

The package on NPM is:

@giancosta86/sync-tools

The public API entirely resides in the root package index, so one shouldn't reference specific modules.

Usage

Barrier

Barrier is just an alias for Promise<void>; however, it must be created via its createBarrier() factory function, which takes the following parameters:

  • requiredTokens: integer number >= 1; it represents the number of tokens that must be cumulated in order to lift the barrier

  • barrierBody: a void-returning function similar to a Promise body, with a fundamental difference:

    • instead of a (resolve, reject) pair, it takes an (addToken, reject) pair.

      addToken() must be called to add a token to the barrier, resolving the Promise as soon as the required number of tokens has been reached

Toy example:

//You can also pass (addToken, reject)
await createBarrier(3, addToken => {
  addToken();
  addToken();

  //Just like in any other Promise, you could
  //even throw to cause a reject()

  //This 3rd token lifts the barrier, resolving the Promise
  addToken();
});