@numbereight/synchronisation
TypeScript icon, indicating that this package has built-in type declarations

1.2.9 • Public • Published

@numbereight/synchronisation

A series of functions to help with synchronisation

Barrier and PromiseBarrier

A standard barrier synchronisation mechanism; the basic notion is: given a size and some function F it provides a function to "hit" the barrier. Once the barrier is hit 'size' times, F is called.

Implementation dependent decisions:

  • Will error if 'hit' (or 'raise' or 'fail') is called when the barrier is already open

API

Barrier(size: number, callback: (error: null | Error) => void): {
    hit: () => void,
    raise: (amount: number) => void,
    fail: (error: Error) => void
}

PromiseBarrier(size: numbergit a): {
    hit: () => void,
    raise: (amount: number) => void,
    fail: (error: Error) => void
} & Promise<void>

PromisePoolBarrier({
    poolsize: number;
    barriersize: number;
    start(index: number): Promise<void>;
}): Promise<void>;

Usage

Barrier:

import { Barrier } from '@numbereight/synchronisation';

function done(error: null | Error) {
    if(error === null) {
        console.log(`Completed Successfully`);
    } else {
        console.log(`Errored`, error);
    }
}

const barrier = Barrier(2, done);

PromiseBarrier:

import { PromiseBarrier } from '@numbereight/synchronisation';

const barrier = PromiseBarrier(2, done);

barrier.then(
    () => console.log(`Completed Successfully`),
    (error) => console.log(`Errored`, error)
);

PromisePoolBarrier:

import { PromisePoolBarrier } from '@numbereight/synchronisation';

const barrier = PromisePoolBarrier({
    poolsize: 2,
    barriersize: 10,
    async start(i: number) {
       // Do my thing 
    }
});

await barrier.catch(e => {
    /* error handling */
    throw e;
})
// All of the PromisePoolBarrier things are now done.

hit

barrier.hit();
// Nothing happens

barrier.hit();
// "Completed Successfully" is printed to console

try {
    // will throw an Error as the barrier is already open
    barrier.hit();
} catch(e) {
    console.log(e);
}

raise

barrier.hit();
// Nothing happens

barrier.raise(2);

barrier.hit();
barrier.hit();
barrier.hit();
// "Completed Successfully" is printed to console

try {
    // will throw an Error as the barrier is already open
    barrier.raise();
} catch(e) {
    console.log(e);
}

fail

barrier.hit();
// Nothing happens

barrier.fail(new Error(`Oh no, it failed`));
// "Errored Error: Oh no, it failed" printed to console (with stack)

try {
    // will throw an Error as the barrier is already open
    barrier.hit();
} catch(e) {
    console.log(e);
}

Package Sidebar

Install

npm i @numbereight/synchronisation

Weekly Downloads

63

Version

1.2.9

License

MIT

Unpacked Size

40.8 kB

Total Files

23

Last publish

Collaborators

  • nechris