3

我计划在我的应用程序后端使用 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 的响应发送。如何等待转换和所有调用完成?

4

1 回答 1

5

您可以使用onDone阅读有关调用承诺的文档

这是一个示例 Express 应用程序,它按顺序等待 2 个 Promise 完成,然后发送该数据:

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

于 2019-06-10T10:45:33.017 回答