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.
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)
– hugomg
I probably don’t, but I can’t think of any other solution right now..
– Paulo Gustavo