Javascript - Settings Steps

Asked

Viewed 58 times

1

I have a problem that is: I need my app to make a number of settings when starting.

I tried to do it using state machine, and I ended up finding this: https://github.com/jakesgordon/javascript-state-machine/

Only it doesn’t allow me to choose where I want the next step to go, only at startup I can define this:

events: [           
        { name: 'start', from: ['none', 'getInformations'], to: 'getInformations' },
        { name: 'getInformations', from: 'getInformations', to: 'getTuner' },
        { name: 'getTuner', from: 'getTuner', to: 'getNetworkInfo' },
        { name: 'getNetworkInfo', from: 'getNetworkInfo', to: 'none' }
      ],

In case, when some stage goes wrong, I can’t go back to her because it was already set where she would go.

I really need to create a configuration step that I have the flexibility to choose where I want to go and that respects asynchronous calls. Does anyone have any tips on how to do that? Without using state machine, the only solution I can think of is:

    while (validacao) {
        switch(estado) {
             case: 0:
                 fazAlgumaCoisa();
                 break;
              case 1:
                  fazOutraCoisa();
                  break;
        }
        }

fazAlgumaCoisa() {
   http.get('blablabla:8080').succes(){
     estado = 1;
}
}

But I don’t see it as an elegant solution.. If someone can give me a light, I really appreciate it..

EDIT: Let’s say I have 4 steps that are mandatory to make my application work and I need to run one after another:

Passo1 -> Passo2 -> Passo3 -> Passo4

However, in step 2, I got an error and I need to make it go to step 2 again.

How could I do that?

EDIT2: After some reading in various places, I arrived at this code (only illustrative examples):

    var nextState = 'stopped';

var states = {

    stopped : function() {
        console.log("in stopped");
        nextState = 'started';

    },

    started : function() {
        console.log("in started");
        nextState = 'finished';
    },

    finished: function () {
        console.log("in finished");
        nextState = 'finished';
        clearInterval(interval);
    }
};

var interval = setInterval(function() {
    states[nextState]();
}, 300);

I’m not sure if this is a good practice and how it behaves in memory, but it seems to me a pleasant solution, given that the setInterval will be destroyed when it arrives at the last stage. In addition, accessing the functions will be extremely fast as I am passing the correct index to the array containing my instructions.

  • 1

    I don’t understand very well what you are trying to do. Can you give a concrete example? (Most likely you don’t need state machine to do what you want but the question is all about state machine)

  • I probably don’t, but I can’t think of any other solution right now..

1 answer

2

You can write your state machine "in hand" using mutually recursive functions:

function faz_coisas(onDone){

    function passo1(){
        umaCoisaAssincrona(function(result){
          blah();
          passo2();
        });
    }

    function passo2(){
        ajax({
           onsuccess: passo3,
           onerror: passo2
        });
    }

    function passo3(){
        outracoisa(function(){
            onDone(meu_resultado);
        });
    }

    passo1();
}

//chamando o inicializador:
faz_coisas(function(result){
   console.log("tá tudo pronto");
});

The basic way to write asynchronous functions in Javascript is through something called "continuation Passing style": its functions call a continuation function rather than returning values normally. In the case of Passo1, Passo2 and Passo3, where the next step is always the same this is quite simple (just call the next step function directly) but in the case of reusable functions like "doing things" you do not know a priori which function runs after you are done. What you can do then is receive this continuation as a parameter (our "onDone").


Now a few more advanced questions: writing the code in continuation-Passing-style we can do anything we want. However, our program is much less structured ugly and boring to write - for example, the Passo2 loop has to be done with a recursive call rather than with a while. In a way, we can say that continuation-Passing-style is a very low level way of programming.

If you want something higher-level and structured, you can take a look at some asynchronous programming library (which uses callbacks or precepts) or, something that is ideal for me, use a code processor that extends the Javascript syntax with generators.

  • Regarding recursiveness, this does not generate memory problems ? The application in which I’m involving this is embedded, and our hardware is kind of old, with few features... I’m going to edit my question and present something I came up with, could you tell me if it’s a good approach ?

  • 1

    It is OK if the functions are always being used asynchronously. For example, if the next step is always after a setTimeout or ajax call

  • Btw, why are you using JS for an embedded application? In my opinion it would be more appropriate to use something like Lua. Lua is much lighter than Javascript, interacts more easily with C or other languages, has tail recursion (you can do recursive functions that never burst the stack) and corroding (you can program asynchronously without having to use callbacks).

  • Because we need to load media done in HTML.. In case, display a . html and load the events contained in this. It is possible to do this using LUA?

  • Well, the events within html are scripted in Javascript so the thing complicates...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.