semaphorecounter
v1.3.0
Published
Enter and exit semaphores, do stuff when done.
Readme
SemaphoreCounter
SemaphoreCounter is a small semaphore like module which allows you to easily do stuff when certain tasks have finished.
$ npm install semaphorecounterUsage
var SemaphoreCounter = require('semaphorecounter');
var sem = new SemaphoreCounter( );
sem.on( 'end', function(){
console.log('done!');
} );
sem.enter();
setTimeout( function(){
sem.leave();
}, 1000 );or even
var SemaphoreCounter = require('semaphorecounter');
var sem = new SemaphoreCounter( );
sem.on( 'end', function(){
console.log('done!');
} );
sem.enter( 'bar' );
sem.enter( 'foo' );
sem.enter( 'bar' );
setTimeout( function(){
console.log( sem.status() ); // -> { bar: 1, foo: 1 }
sem.leave( 'foo' );
console.log( sem.status() ); // -> { bar: 1, foo: 0 }
}, 2000 );
setTimeout( SemaphoreCounter.bound( 'leave', sem, 'bar' ), 100 );
setTimeout( function(){
sem.leave( 'bar' );
}, 3000 );
console.log( sem.status() ); // -> { bar: 2, foo: 1 }Methods and Constructors
The module exposes a single function, which is a constructor for an object of prototype SemaphoreCounter. Each instance is an event emitter, and exposes the following methods:
enter: call when 'entering' a semaphoreleave: call when 'leave' a semaphorestatus: get status on specific semaphore, or all of them
<semaphore>.enter( [key] )
Arguments: key (string, optional): the name of the semaphore to increment.
<semaphore>.leave( [key] )
Arguments: key (string, optional): the name of the semaphore to decrement.
If, when leave-ing all semaphores for the SemaphoreCounter object are 0, the SemaphoreCounter object emits an end event.
<semaphore>.status( [key] )
Arguments: key (string, optional): the name of the semaphore to return the status of -- when omitted, returns the status of all of them
Returns: Number counter for key, or Object (with a property per semaphore and the status of that semaphore as value) when no key was specified.
<semaphore>.bound.enter( [key] ) and <semaphore>.bound.leave( [key] )
If the only thing you're doing in a callback is entering or leaving a counter, the bound property on a semaphore counter object exposes some pre-bound methods for enter and leave under these names, which allows you to make your code shorter and more legible. In other words, it allows you to go from this...
setTimeout( function(){
sem.leave( 'bar' );
}, 100 );... to this ...
setTimeout( sem.bound.leave( 'bar' ), 100 );... for both enter and leave.
Events
Each SemaphoreCounter object can emit 3 events: end, entered and left:
endis emitted when all counters are balanced - that is, for eachleave, there was aenteron the same key. (Remember you can look up the status of the SemaphoreCounter withstatus)enteredis emitted when a counter is entered - that is,enteris called. It receives thekeyas the only argument.leftis emitted when a counter is left - that is,leaveis called. It receives thekeyas the only argument.
