SerialChain
Description
SerialChain is a module I wrote to so that I could write pretty code.
I like writing chains and really wanted to be able to do it with asynch code. There are a couple other options out there that already do this, but I wanted to learn how to write my own so I made this one.
Installation
npm install serialchain
npm install ben-bradley/serialchain
Concepts & Use
- You create a
chain
:
var chain = new SerialChain({ methodA: function(a, done) {
// do something
done(err, a);
}})
- You
add()
links to thechain
.
chain.add('methodB', function(b, done) {
// do something else
done(err, b);
});
- You can then compose and execute your
chain
chain
.methodB('xyz')
.methodA('abc').timeout(1500)
.done(function(err, results) {
if (err)
throw err;
console.log(results); // => [ 'xyz', 'abc' ]
});
this.locals
I found that I needed to have an easy way to pass variables between my chained methods so I added the locals
property/namespace to the chain
.
var chain = ; chain; chain; chain ;
Built-in Methods
-
SerialChain()
- Returns a new
chain
. - Accepts an
Object
to add to the chain:
var chain = new SerialChain({ methodName: callback });
- Added method
callback
s have the signature:
function([arguments, from, chain, call, ]done) { // ... }
- Returns a new
-
add()
- This method adds other methods (links) to your
chain
- Accepts arguments as an
Object
:
chain.add({ methodName: callback });
- Also accepts
String
andFunction
chain.add('methodName', callback);
- Added method
callback
s have the signature:
function([arguments, from, chain, call, ]done) { // ... }
- This method adds other methods (links) to your
-
timeout()
- Calling this method after an
add()
ed method will set a timeout on the previously called method. - Arguments are a
Number
of ms to wait
chain .methodA('a').timeout(1000) // will wait 1 second and bail .methodB('b') .done(function(err, results) { // ... });
- Calling this method after an
-
done()
- This method triggers the execution of the
chain
. - Arguments are a callback:
chain .methodA('a') .methodB('b') .done(function(err, results) { // ... })
- This method triggers the execution of the
Example
var SerialChain = ; var chain = { ; } { ; }; chain; chain; chain; chain // thingOne() will complete in 100ms so this timeout will pass ;
Tests
$ npm install && npm test
Version History
- 0.0.8 - Ensured that errors are promoted to be a
new Error()
- 0.0.7 - Added code to clean up
_chain
whendone()
is called - 0.0.6 - Added
locals
namespace to pass vars between methods - 0.0.5 - Calling
done()
without args in anadd()
ed method doesn't populate results. - 0.0.4 - Version bump, added Travis-CI.
- 0.0.3 - Added
timeout()
. - 0.0.2 - Refactored to
serialchain
. - 0.0.1 - Removed
async
dependency. - 0.0.0 - Initial drop.
Other Options
- continue - https://www.npmjs.org/package/continue - I took a lot of design ideas from this package, but it operates against a collection.