async-event
Simple async event handling and interception.
Install
npm install --save async-event
Usage
Requires a promise implementation to be global
var AsyncEvent = require('async-event');
var user = { id: 123 };
var event = new AsyncEvent(user);
myPubSub.publish('my-event', event);
event
.then(function() {
console.log('Passed async validation!');
})
.catch(function() {
console.log('Failed async validation :(');
});
myPubSub.subscribe('my-event', function(event) {
event.intercept(function(user) {
return fetch('/user/123/validate', {
method: 'POST',
body: JSON.stringify(user)
});
})
});
API
AsyncEvent(value, promise) ⇒ AsyncEvent
The constructor.
Param | Type | Description |
---|
value | any | The initial value |
promise | Promise | An optional starting promise |
intercept(handler) ⇒ void
A function that can perform a sync or async task. Handlers are executed in serial order.
Param | Type | Description |
---|
handler | Function | The intercept function |
getValue() ⇒ any
Gets the initial value the event initialized with.
then(fn) ⇒ Promise
Delegates to the internal Promise. Subscribes to the chain at that point in time. This
will not add to the chain. This can be used to perform a task that you would want to happen
in parallel.
Param | Type | Description |
---|
fn | Function | The promise function |
catch(fn) ⇒ Promise
Same as then
except the catch equivalent.
Param | Type | Description |
---|
fn | Function | The promise function |