@ChangeState
Signature
function ChangeState( from: string | string[], to: string, opt?: ChangeOption): (target: any, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<any>) => voidParameters
from: string | string[]
Allowed starting state(s).
| Value | Meaning |
|---|---|
'idle' | only 'idle' |
['a', 'b'] | either 'a' or 'b' |
FSM.INIT | i.e. '[*]', the initial state |
[] (empty) | any state, and aborts an in-flight MiddleState |
On mismatch, throws FSMError:
{className} {action} to {to} failed: current state {state} not from {from}to: string
Target state. The stable state after a successful transition.
opt?: ChangeOption
See ChangeOption.
Decorated behavior
The decorated method is replaced with this flow:
- If
opt.contextis set,fsm = FSM.get(context)(composition mode) - If already in
to: return immediately (async:Promise.resolve(cached), sync:cached) - If currently in a
MiddleStatematchingopt.abortAction: callmiddle.abort(fsm) - Validate
from; on mismatch return the error (reject / throw / return, depending onignoreErrorandsync) - Create
MiddleState(old, to, action)and callsetState(middle)(enter intermediate) - Run the original method
- Returns Promise:
.then(success).catch(failed) - Returns sync value:
success(result)(async wrapsPromise.resolve, sync returns directly)
- Returns Promise:
success: cache result; if not aborted,setState(to); triggeropt.successfailed:setState(old, err); triggeropt.fail; return the error
stateDiagram metadata
When applied, @ChangeState registers {from, to, action} metadata in the module-level stateDiagram Map (only when opt.context is not set), for the FSM.prototype.stateDiagram getter to generate mermaid edges.
Example
class Conn extends FSM { @ChangeState(FSM.INIT, 'connected', { action: 'connect', success: (r) => console.log('connected'), fail: (e) => console.error(e) }) async connect() { return await api() }}