branches

Node.js flow control system for promises

npm install branches
6 downloads in the last week
12 downloads in the last month

Branches.js

Flow control library for Node.js

Branches.js is a simple flow control library for Node.js (nodejs.org).

Branches.js is very much a work in progress. I had some ideas of how to implement a flow control library for some asynchronous javascript code I was writing. I'm not certain this is the best implementation, but it quickly got the job done. I plan to implement other approaches, but I found this approach fairly simple to start with. I also plan to eventually remove the hard dependencies on Kris Zyp's promise implementation packaged by MaxMotovilov (node-promise), but I'm very thankful for the library to quickly put this flow control library together.

For the future, I want to explore less intrusive methods for consumer's functions (i.e. don't require intrusive deferred and promises). I'm not certain this is possible with this simple approach, so feedback is very welcome.

Ideas, suggestions, help, etc. are very welcomed. This is my first real attempt at my own javascript library

For some examples, try running test.js with different structure objects uncommented.

Installation

npm install branches

Looking at the usage example below, the flow of our asynchronous code would be:

  • Run foo
    • If foo is successful, then run bar
      • If bar is successful, then run baz
      • If bar fails, then run bad
    • If foo fails, then run an empty function

We plop this structure as a hash into our Branches constructor along with a hash of the functions to get a new Branches instance. Then, we call the run method on our instance to run the flow structure. When the flow structure finishes with whichever trajectory it took, our Branches instance emits a complete event.

Usage

var Branches = require('branches');

var structure = {
    'foo': {
        'bar': ['baz', 'bad']
    }
};

var fns = {
    'foo': function() {
        console.log('foo');

        // use defers and promises to make this work for now
        var dfd = Branches.defer();

        setTimeout(function() {
            dfd.resolve();        // so we'll go to `bar`
        }, 4000);

        return dfd.promise;
    },

    'bar': function() {
        console.log('bar');

        // use defers and promises to make this work for now
        var dfd = Branches.defer();

        setTimeout(function() {
            dfd.reject();         // so we'll go to `bad`
        }, 4000);

        return dfd.promise;
    },

    'baz': function() {
        // etc
    },

    'bad': function() {
        // etc
    }
};

// Run it
var branches = new Branches(structure, fns);
branches.run();
branches.on('complete', function() {
    console.log('all done');
});

// Or a little sugar...
Branches(structure, fns).run().on('complete', function() {
    console.log('all done');
});
npm loves you