matthewp / robot

🤖 A functional, immutable Finite State Machine library

Home Page:https://thisrobot.life

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

mpenna opened this issue · comments

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.

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!

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

Thanks!