'Invoke a service from a "serverless" fsm (Xstate)

I'm using xsate on a Node.JS backend. Here is the current flow :

  • State is rehydrated (Initialized or fetched from DB)
  • Event is sent to the FSM
  • State is serialized to DB

Here is some pseudo code

const state  = db.fetch(flowId) ?? machine.initialState;
 // Use State.create() to restore state from a plain object
const previousState = State.create<DefaultContext, MyEvent>(stateDefinition);
// Use machine.resolveState() to resolve the state definition to a new State instance relative to the machine
const resolvedState = machine.resolveState(previousState);
const interpreter = interpret(machine).start(resolvedState);
onst newState: State<DefaultContext, MyEvent, any, Typestate<DefaultContext>> = interpreter.send(event);
db.saveState(flowId, newState);

My question is : Is it possible to Invoke a Promise ?

I would like to keep my FSM "alive" if I have pending promises. The goal is to modify the context based on the promise result. Is there some hook I could use ?

Thanks for any advise.



Solution 1:[1]

You can now use the new waitFor(...) helper in the latest version of XState to asyncronously wait for a state machine to reach some condition, like a specific state.

In your situation, the predicate would be something like state.matches('yourSuccessState').

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Khourshid