如果我的 action creator return promise,Redux 什么时候解决调度?

When does Redux resolve a dispatch if my action creator return promise?

This post,Dan 写了一个片段来演示异步操作。

我想知道 Redux 怎么知道我的 store 已经完全更新了?

是否有可能 fetchedUser 在执行 dispatch(getUser(userId)).then 期间尚未更新?

如果我写会发生什么 setTimeout(()=>{ dispatch({ type: 'GET_USER_SUCCESS', id, response }) }, 5000)fetchUser.then 中?

export function getUser(id) {
  return dispatch => {
    dispatch({ type: 'GET_USER_REQUEST', id })

    // Perform the actual API call
    return fetchUser().then(
      response => {
        // Reducers may handle this to show the data and reset isFetching
        dispatch({ type: 'GET_USER_SUCCESS', id,  response })
      },
      error => { ... }
    )
  }
}



export function getUserAndTheirFirstPost(userId) {
  return (dispatch, getState) => {
    return dispatch(getUser(userId)).then(() => {
      // Assuming this is where the fetched user got stored
      const fetchedUser = getState().usersById[userId]

      // Assuming it has a "postIDs" field:

      const firstPostID = fetchedUser.postIDs[0]

      return dispatch(getPost(firstPostID))
    })
  } 
}

请指导我。

谢谢

Redux 是一个以反应方式工作的库,因此它等待分派操作以将状态更改传播到所有连接的函数。

如果你设置一个 5 秒的超时时间来调度一个动作,对于 Redux 来说这和你在现实生活中等待 5 秒然后调用 dispatch() 是一样的。它只会通过更新所有连接的函数来响应该操作。

你的问题更多是关于承诺。

Is there a chance that fetchedUser has not updated yet during executing dispatch(getUser(userId)).then ?

不,因为您在 getUser 操作之后使用 .then,这是为了确保 fetchUser 承诺已经解决。可能会发生找不到用户或类似情况,但在该块中,您可以确保 fetchUser 调用已经完成。

流程是这样的:

  1. 调用 getUser(userId)
  2. 调度GET_USER_REQUEST
  3. 调用 fetchUser()
  4. 等到 fetchUser 完成。
  5. 调度GET_USER_SUCCESS
  6. 运行 fetchedUser = getState().usersById[userId]
  7. 等等..

What will happen if I write setTimeout(()=>{ dispatch({ type: 'GET_USER_SUCCESS', id, response }) }, 5000) in fetchUser.then

在这种情况下,它 可以 运行 fetchedUser 分配行而不更新状态,因为我假设设置用户的是 GET_USER_SUCCESS行动对吧?因此,如果请求完成时间少于 5 秒,它将 运行 在使用用户数据更新状态之前进行分配。