Skip to content

patbenatar/promise-state-machine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Promise State Machine

npm version Code Climate Test Coverage

var fsm = new PromiseStateMachine({
  initial: 'green',
  events: {
    warn: { from: 'green', to: 'yellow' },
    panic: { from: ['green', 'yellow'], to: 'red' },
    calm: { from: 'red', to: 'yellow' },
    clear: { from: ['yellow', 'red'], to: 'green' }
  }
});

fsm.on('warn', function(event, from, to, anyArgs) {
  return Promise.resolve('result 1');
});

fsm.on('warn', function(event, from, to, anyArgs) {
  var transaction = anyArgs[0];
  var somethingElse = anyArgs[1];

  return Promise.resolve('result 2');
});

fsm.warn(transaction, somethingElse).then(function(results) {
  // results: ['result 1', 'result 2']
}).error(function(error) {
  // could receive a StateTransitionError if trying to transition via an
  // inaccessible event.
});

fsm.is('green'); // => false
fsm.is('yellow'); // => true
fsm.state(); // => 'yellow'
fsm.can('calm'); // => false
fsm.can('panic'); // => true

Extending an existing object

var MyObject = function() {
  PromiseStateMachine.call(this, {
    initial: 'green',
    events: {
      warn: { from: 'green', to: 'yellow' },
      panic: { from: 'yellow', to: 'red' },
      calm: { from: 'red', to: 'yellow' },
      clear: { from: 'yellow', to: 'green' }
    }
  });
};

_.extend(MyObject, PromiseStateMachine);
_.extend(MyObject.prototype, PromiseStateMachine.prototype);

var fsm = new MyObject();
fsm.is('green'); // => true
fsm.warn().then(function() {
  fsm.is('green'); // => false
});

About

An event-driven finite state machine backed by Promises

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published