首页 > 其他 > 详细

[XState] Invoking a Promise for Asynchronous State Transitions in XState

时间:2020-01-21 18:28:22      阅读:76      评论:0      收藏:0      [点我收藏+]

Unbeknownst to many, promises are state machines. They exist in either an idlependingresolved 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

原文:https://www.cnblogs.com/Answer1215/p/12222471.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!