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


    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'
          }
        }
      }
    })
  • 相关阅读:
    C. MP3(离散化 暴力)
    最大团、最小独立集
    欧拉函数
    In Touch(dijk+并查集优化)
    Path(2019 杭电多校第一场 ) hdu 6582(最短路模板+dinic模板)
    2019 南昌邀请赛 Winner (tarjan缩点)
    mybatis主键回填和自定义
    mybatis配置xml文件的层次结构
    Paratroopers
    Dual Core CPU
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12222471.html
Copyright © 2020-2023  润新知