javascript-state-machine
javascript-state-machine copied to clipboard
Init state machine with async transitions
I'm using state machine for telegram bot, when webhook received message from telegram i get user state from store (redis), next creating state machine:
//example of user state from store
fsmState = {state: 'initial', data: {}}
const fsm = new StateMachine({
data: fsmState.data,
init: fsmState.state,
transitions: [
//some transitions
],
methods: {
onAfterTransition: async lifecycle => {
if (fsmState.state !== lifecycle.to) {
fsmState = await this.setUserFsmState(userId, {...fsmState, state: lifecycle.to});
}
},
//some other transitions and state lifecycle methods
},
});
next i'm parsing telegram message based on user state and wanna make some transition:
fsm[camelCase(transition)]();
but received pending transition error, because of promised onAfterTransition.
How can i wait while StateMachine is ready to make transition? Now i'm using awfull code:
const waitFor = () => setTimeout(() => {
if (fsm.can(transition)) {
fsm[camelCase(transition)]();
} else {
waitFor();
}
}, 10);
waitFor();