Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<title>State Machine: Generator Coroutines (asynquence)</title>
</head>
<body>
<h1>State Machine: Generator Coroutines (asynquence)</h1>
<p>hint: look in the console</p>
<script src="https://rawnpm.getify.io/asynquence/latest/asq.js"></script>
<script src="https://rawnpm.getify.io/asynquence-contrib/latest/contrib.js"></script>
</body>
</html>
 
// noprotect
function state(val,handler) {
    // make a coroutine handler for this state
    return function*(token) {
        // state transition handler
        function transition(to) {
            token.messages[0] = to;
        }
        // set initial state (if none set yet)
        if (token.messages.length < 1) {
            token.messages[0] = val;
        }
        // keep going until final state (false) is reached
        while (token.messages[0] !== false) {
            // current state matches this handler?
            if (token.messages[0] === val) {
                // delegate to state handler
                yield *handler(transition);
            }
            // transfer control to another state handler?
            if (token.messages[0] !== false) {
                yield token;
            }
        }
    };
}
// counter (for demo purposes only)
var counter = 0;
ASQ( /* optional: pass an initial state value here */ )
// run our state machine, transitions: 1 -> 4 -> 3 -> 2
.runner(
    // state `1` handler
    state(1,function*(transition){
        console.log("in state 1");
        yield ASQ.after(1000); // pause state for 1s
        yield transition(4); // goto state `4`
    }),
    // state `2` handler
    state(2,function*(transition){
        console.log("in state 2");
        yield ASQ.after(1000); // pause state for 1s
        // for demo purposes only, keep going in a
        // state loop?
        if (++counter < 2) {
            yield transition(1); // goto state `1`
        }
        // all done!
        else {
            yield "That's all folks!";
            yield transition(false); // goto terminal state
        }
    }),
    // state `3` handler
    state(3,function*(transition){
        console.log("in state 3");
        yield ASQ.after(1000); // pause state for 1s
        yield transition(2); // goto state `2`
    }),
    // state `4` handler
    state(4,function*(transition){
        console.log("in state 4");
        yield ASQ.after(1000); // pause state for 1s
        yield transition(3); // goto state `3`
    })
)
// state machine complete, so move on
.val(function(msg){
    console.log(msg);
});
Output 300px

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
getifypro
0viewers