matthewp / robot

🤖 A functional, immutable Finite State Machine library
https://thisrobot.life
BSD 2-Clause "Simplified" License
1.92k stars 88 forks source link

How to start and await for a state machine's asynchronous execution? #206

Open mpenna opened 12 months ago

mpenna commented 12 months ago

I have this scenario where the state machine will be frequently triggered/started by an external process (e.g.: a cron-like task manager), which will need to block until whatever asynchronous processing the state machine has been configured to execute finishes. Is this achievable? State would be serialized/persisted and pulled/hydrated back upon every triggered execution. However, I'm not sure how the blocking of the external (controller) process would be handled.

Thanks.

matthewp commented 12 months ago

Your finish is "finished" when it hits a final state, a state which has no transitions. What I would probably do is something like this:

let resolve;
let promise = new Promise(_resolve => {
  resolve = _resolve;
})

service = interpret(machine, () => {
  if(machine.state.value.final) {
    resolve();
  }
});

await promise;
// All done!
mpenna commented 12 months ago

Nice! Let me try that strategy out and see how it goes.

Thanks!