[XState] Invoking a Promise for Asynchronous State Transitions in XState
Posted answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[XState] Invoking a Promise for Asynchronous State Transitions in XState相关的知识,希望对你有一定的参考价值。
Unbeknownst to many, promises are state machines. They exist in either an idle
, pending
, resolved
or rejected
state. Because they can be modeled as state machines, we can invoke them when we enter a state in a Machine
.
We invoke services such as a promise by using the invoke
property on a state node. When the state is entered, the src
of the invoke
object is called. In the case of promises, the Promise
is called. When the Promise
resolves, the onDone
transition is taken. When the Promise
rejects, the onError
transition is taken. In either case, the data returned from the promise, whether resolved or errored, is passed back on the event object as event.data
.
const fetchPeople = () => { return fetch(‘https://swapi.co/api/people/1‘) .then(res => res.json()) } const cuteAnimalMachine = Machine({ id: ‘swapi‘, initial: ‘idle‘, context: { people: null, error: null }, states: { idle: { on: { FETCH: ‘loading‘ } }, loading: { invoke: { id: ‘fetchPeople‘, src: fetchPeople, onError: { target: ‘retry‘, actions: [ assign({ error: (ctx, event) => event.data }) ] }, onDone: { target: ‘success‘, actions: [assign({ people: (ctx, event) => event.data })] } } }, success: { type: ‘final‘ }, retry: { on: { FETCH: ‘loading‘ } } } })
以上是关于[XState] Invoking a Promise for Asynchronous State Transitions in XState的主要内容,如果未能解决你的问题,请参考以下文章
[XState] Invoke Callbacks to Send and Receive Events from a Parent XState Machine
[XState] Use an Interpreter to Instantiate a Machine
转-Cannot refer to an instance field arg while explicitly invoking a constructor
There is an error in invoking javac. A full JDK (not just JRE) is required