ifandelse / machina.js

js ex machina - finite state machines in JavaScript
http://machina-js.org/
Other
1.93k stars 147 forks source link

this.handled is synchronous? #124

Closed SubaruWRX55 closed 6 years ago

SubaruWRX55 commented 8 years ago

Is it by design that this.handle runs synchronously? Take this example:

var vehicleSignal = new machina.Fsm( {
    initialize: function( options ) {
    },
    namespace: "vehicle-signal",
    initialState: "uninitialized",
    states: {
        uninitialized: {

            "*": function() {

                this.transition( "green" );
            }
        },
        green: {
            _onEnter: function() {
                console.log('green enter start');
                this.handle( "next" );
                console.log('green enter end');
                console.log('current state', this.state)
            },
            next: "yellow",

            _onExit: function() {
                console.log('green exit');
                console.log('current state', this.state);
            }
        },
        yellow: { },

    },

   } );

The out put is:

green enter start
green exit
current state green
green enter end
current state yellow

So in order for the green state _onEnter to finish before transitioning to yellow, we need to always put this.handle in a setImmediate.

green: { 
        _onEnter: function() {
                console.log('green enter start');
                setImmediate(function() {
                     this.handle( "next" );
                }.bind(this));
                console.log('green enter end');
                console.log('current state', this.state)
            },

then the work flow looks right:

green enter start
green enter end
current state green
green exit
current state green

Am I using the package correctly?

ifandelse commented 6 years ago

@SubaruWRX55 Sincere apologies for the long delay (see #146). Yes - you are using it correctly, for what it's worth. I've debated a lot about making handle async in the next major version bump. I'm still open to it, but I need to think through the implications before I'm committed to it.