javascript-state-machine icon indicating copy to clipboard operation
javascript-state-machine copied to clipboard

Init state machine with async transitions

Open bbird1980 opened this issue 4 years ago • 0 comments

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();

bbird1980 avatar Dec 13 '20 02:12 bbird1980