barrier
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()
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()
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())
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())
setTimeout(() => {
console.log(await barrier())
}, 2000)
Don't
Do not wait twice for the same barrier in the same event. It will
never resolve
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