M
M
mejedi2013-02-20 23:14:13
Node.js
mejedi, 2013-02-20 23:14:13

State machine with "inertia" in node.js?

Please tell me what is the most correct way to design an API in the following situation.
There is some object that is in one of the predefined states S={s 1 …s n }. There is also a method(s) that change the state of an object. To move from one state to another, you need to execute a chain of asynchronous calls, that is, switching states does not occur instantly.
In fact, the state set looks like S'=S∪{s transitional }. Until the transition is completed, the object is in a transitional state (s transitional). In a transitional state, you cannot call methods that initiate a new state transition. What to do if such a call did occur is an open question (for example, you can return an error immediately, or put it in a queue).
Is there any standard solution in this situation?
I tend to have the client know about the state change not through the callback passed to the method, but through the EventEmitter interface . Inside the object, maintain a pair of <S real ,S target >: the real state, which changes with a delay, and the "target" state, which is set instantly.
PS. In my task, "object" is an interface to a digital camera.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vyacheslav Slinko, 2013-02-21
@KeepYourMind

I would use queue and series from the async library .

M
Mezomish, 2013-02-21
@Mezomish

Of course, there is no "standard" solution, it all depends on the specific implementation.
In the simplest case, you can make a banal queue of transitions, i.e. a new transition is not called immediately, but only after the previous one has completely ended. The disadvantages are obvious - UI lag is possible, when the reaction to user actions occurs with a delay. Pros: Easier to implement.
Or you can take the Qt Animation Framework as an example, in which this is done quite elegantly: there the transition from state to state is separate, and visual animations are separate. And there are no intermediate states. Thus, when the command “go to such and such a state”, the switching occurs instantly, and the animation at this moment is just starting.
If the animation has not yet ended, but the command for the next transition is already received, then the state switching itself occurs again instantly, and the animation “adjusts” to the new data: the old animation does not end, but stops at the place where the new command found it, and already from this position the animation starts up to the new point. Cons: More difficult to implement. Pros - very beautiful and natural :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question