本文介绍了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
更多推荐
XState:等待调用函数的响应
发布评论