@strong-roots-capital/barrier
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

barrier Build status npm version codecov

A TypeScript implementation of the synchronization primitive

Install

npm install @strong-roots-capital/barrier

Use

Create a barrier to suspend the current executing-context

import barrier from '@strong-roots-capital/barrier'
const barrier = makeBarrier()

The default barrier (without arguments) waits for one additional executing-context to reach the same barrier before resolving the barrier and allowing the current executing-context to proceed.

const barrier = makeBarrier()
setTimeout(() => {barrier()}, 1000)

await barrier()
// will resolve after timeout invokes `barrier()`

A barrier is an ordinary Promise, so you can also use .then

const barrier = makeBarrier()
setTimeout(() => {barrier()}, 1000)

await barrier()
barrier().then(() => console.log('barrier has resolved'))

The optional numeric argument to makeBarrier describes the number of executing-contexts required to reach the barrier before resolving

const barrier = makeBarrier(2)
setTimeout(() => {barrier()}, 1000)
setTimeout(() => {barrier()}, 1500)

await barrier()
// will resolve after both timeouts invoke `barrier()`

Resolving values

Values can be resolved through the barrier (order will be preserved)

const barrier = makeBarrier<string>(2)
setTimeout(() => {barrier('one')}, 1000)
setTimeout(() => {barrier('two')}, 1500)

console.log(await barrier())
//=> ['one', 'two']

Excessive calls

Excessive calls to the barrier will not have any effect; a resolved promise will be returned

const barrier = makeBarrier<string>(2)
setTimeout(() => {barrier('one')}, 1000)
setTimeout(() => {barrier('two')}, 1500)
setTimeout(() => {barrier('three')}, 2000)

console.log(await barrier())
//=> ['one', 'two']

setTimeout(() => {
    console.log(await barrier())
    //=> ['one', 'two']
}, 2000)

Don't

Do not wait twice for the same barrier in the same event. It will never resolve

// don't do this
const barrier = makeBarrier()
await barrier()
await barrier()

FAQ

Why yet-another barrier?

There are several barrier implementations on npm, unfortunately, I couldn't find any that fit my needs:

  • Strongly-typed with generics
  • Resolves values from executing-contexts reaching the barrier
  • Simple invocation
  • Unsurprising behavior
  • Well-maintained
  • Comprehensive test suite

For the packages I found, pick 3 of these.

Acknowledgments

This project was heavily inspired by the following packages

Package Sidebar

Install

npm i @strong-roots-capital/barrier

Weekly Downloads

18

Version

1.0.1

License

ISC

Unpacked Size

9.87 kB

Total Files

4

Last publish

Collaborators

  • amchelle
  • hamroctopus