XState:等待调用函数的响应 [英] XState: Wait for response of invoked function

查看:29
本文介绍了XState:等待调用函数的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我计划使用XState来管理应用程序后端的状态。调用API时,会在状态更改成功时调用函数。函数调用的结果必须作为API的响应返回。

// Returns a Promise, e.g.:
// {
//   id: 42,
//   name: 'David',
//   friends: [2, 3, 5, 7, 9] // friend IDs
// }
function getUserInfo(context) {
return fetch('/api/users/#{context.userId}').then(response =>
 response.json()
);
}

// Returns a Promise
function getUserFriends(context) {
const { friends } = context.user;

return Promise.all(
 friends.map(friendId =>
  fetch('/api/users/#{context.userId}/').then(response => response.json())
  )
 );
}

const friendsMachine = Machine({
 id: 'friends',
 context: { userId: 42, user: undefined, friends: undefined },
 initial: 'gettingUser',
 states: {
  gettingUser: {
   invoke: {
    src: getUserInfo,
    onDone: {
      target: 'gettingFriends',
      actions: assign({
        user: (context, event) => event.data
      })
    }
   }
  },
  gettingFriends: {
   invoke: {
    src: getUserFriends,
    onDone: {
      target: 'success',
      actions: assign({
        friends: (context, event) => event.data
      })
    }
   }
  },
 success: {
  type: 'final'
 }
}
});


interpret(friendsMachine).start()

我希望getUserFriends的输出作为我的API的响应发送。如何等待转换和所有调用完成?

推荐答案

您可以使用onDone(read the docs on invoking promises 📖)

这里有一个Express应用示例,它按顺序等待2个承诺完成,然后发送数据:

function eventuallyGet(value) {
  return new Promise(res => {
    setTimeout(() => {
      res(value);
    }, 1000)
  })
}

const getUserMachine = Machine({
  initial: 'fetchingName',
  context: {
    user: undefined
  },
  states: {
    fetchingName: {
      invoke: {
        src: () => eventuallyGet('David'),
        onDone: {
          target: 'fetchingDetails',
          actions: assign({
            user: (ctx, e) => ({
              ...ctx.user,
              name: e.data
            })
          })
        }
      }
    },
    fetchingDetails: {
      invoke: {
        src: () => eventuallyGet({ location: 'Florida' }),
        onDone: {
          target: 'success',
          actions: assign({
            user: (ctx, e) => ({
              ...ctx.user,
              ...e.data
            })
          })
        }
      }
    },
    success: {
      type: 'final',
      data: {
        user: ctx => ctx.user
      }
    }
  }
});

app.get('/user', function(request, response) {
  interpret(getUserMachine)
    .onDone(e => {
      response.json(e.data);
    })
    .start();
});

您可以在这里看到代码:https://glitch.com/~pleasant-relish

这篇关于XState:等待调用函数的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆