From 87d7216eb9e6385a2975384808500e2abbc4aa96 Mon Sep 17 00:00:00 2001 From: Erik Huelsmann Date: Sat, 14 Dec 2024 14:31:21 +0100 Subject: [PATCH] Add guide from issue #206 (#228) Add guide from issue #206 Closes #206 Co-authored-by: Matthew Phillips --- docs/guides.md | 3 +- .../guides/awaiting-asynchronous-execution.md | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 docs/guides/awaiting-asynchronous-execution.md diff --git a/docs/guides.md b/docs/guides.md index fe09dd01b..7dd845a06 100644 --- a/docs/guides.md +++ b/docs/guides.md @@ -9,4 +9,5 @@ These guides are meant to help you along your journey learning Finite State Mach * __[Composition](./guides/composition.html)__: How to use functional composition when building state machines, to maximize code reuse where possible. * __[Nested States](./guides/nested-states.html)__: Create machines with nested states by [invoking](./api/invoke.html) other machines. -* __[Comparison with XState](./guides/comparison-with-xstate.html)__: Differences and tradeoffs between Robot and [XState](https://xstate.js.org). \ No newline at end of file +* __[Awaiting asynchronous completion](./guides/awaiting-asynchronous-completion.html)__: How to await a machine to enter a `final` state. +* __[Comparison with XState](./guides/comparison-with-xstate.html)__: Differences and tradeoffs between Robot and [XState](https://xstate.js.org). diff --git a/docs/guides/awaiting-asynchronous-execution.md b/docs/guides/awaiting-asynchronous-execution.md new file mode 100644 index 000000000..340817c6f --- /dev/null +++ b/docs/guides/awaiting-asynchronous-execution.md @@ -0,0 +1,30 @@ +--- +layout: page.njk +title: Awaiting asynchronous execution +tags: guide +permalink: guides/awaiting-asynchronous-execution.md +--- + +In a scenario where it's necessary to `await` the machine to enter a `final` +state (a state which has no transitions), the `onChange` callback (the second argument to `interpret`) can be used +to resolve a promise. The promise can be externally awaited. + +```js +let resolve; +let promise = new Promise(_resolve => { + resolve = _resolve; +}) + +service = interpret(machine, () => { + if(machine.state.value.final) { + resolve(); + } +}); + +await promise; +// All done! +``` + +This is particularly useful for state machines which consist entirely +of `immediate` and `invoke` states: these model execution flows which do +not depend on external events for their execution and state transition.