Skip to content

Commit 0409089

Browse files
authored
Add docs explaining how to 'cancel' invoke() (#223)
Add docs explaining how to 'cancel' invoke() Closes #185
1 parent 2b92e9b commit 0409089

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

.changeset/tender-humans-brush.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"robot3": patch
3+
---
4+
5+
Documentation for advanced use of 'invoke()'

docs/api/invoke.md

+31
Original file line numberDiff line numberDiff line change
@@ -196,3 +196,34 @@ const machine = createMachine({
196196
error: state()
197197
})
198198
```
199+
200+
## Cancellation
201+
202+
JavaScript does not support cancellation of promises: the action which will
203+
resolve the promise will run to completion or until it encounters an error.
204+
205+
There are situations where the result of the promise no longer matters. The
206+
machine should proceed to a different action, or simply stop changing state
207+
entirely. To achieve this with the `invoke` state, an extra event can be
208+
added to the state like the `cancel` event in the example below.
209+
210+
```js
211+
import { createMachine, invoke, reduce, state, transition } from 'robot3';
212+
213+
const loadTodos = () => Promise.reject("Sorry but you can't do that");
214+
215+
const machine = createMachine({
216+
start: invoke(loadTodos,
217+
transition('cancel', 'cancelled'),
218+
transition('done', 'loaded',
219+
reduce((ctx, ev) => ({ ...ctx, todo: ev.data }))
220+
)
221+
),
222+
cancelled: state(),
223+
loaded: state()
224+
})
225+
```
226+
227+
By moving out of `start` state before the promise returned by `loadTodos`
228+
resolves, the function result will be discarded: the machine finds that it
229+
is no longer in the state from which is was invoked and discards the event.

0 commit comments

Comments
 (0)