XState:等待调用函数的响应

编程入门 行业动态 更新时间:2024-10-25 18:34:17
本文介绍了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:等待调用函数的响应

本文发布于:2023-08-07 18:15:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1320821.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   XState

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!