Redux thunk:return promise from dispatched action

Redux thunk: return promise from dispatched action

是否可以从 action creator return promise/signal,当 Redux thunk 成功派发特定 action 时解决?

考虑这个动作创建者:

function doPost(data) {
    return (dispatch) => {
        dispatch({type: POST_LOADING});
        Source.doPost() // async http operation
            .then(response => {
                dispatch({type: POST_SUCCESS, payload: response})
            })
            .catch(errorMessage => {
                dispatch({type: POST_ERROR, payload: errorMessage})
            });
    }
}

我想在 Redux 调度 POST_SUCCESS 调用 doPost 动作创建器后异步调用组件 中的某些函数 或 POST_ERROR 个动作。一种解决方案是将回调传递给 action creator 本身,但这会使代码变得混乱并且难以掌握和维护。我也可以在 while 循环中轮询 Redux 状态,但那样效率很低。

理想情况下,解决方案应该是一个承诺,它应该 resolve/reject 当某些动作(在本例中为 POST_SUCCESS 或 POST_ERROR)被调度时。

handlerFunction {
  doPost(data)
  closeWindow()
}

上面的例子应该重构,所以只有在 doPost() 成功时才调用 closeWindow()。

当然,您可以 return 从异步操作中承诺:

function doPost(data) {
    return (dispatch) => {
        dispatch({type: POST_LOADING});
        // Returning promise.
        return Source.doPost() // async http operation
            .then(response => {
                dispatch({type: POST_SUCCESS, payload: response})
                // Returning response, to be able to handle it after dispatching async action.
                return response;
            })
            .catch(errorMessage => {
                dispatch({type: POST_ERROR, payload: errorMessage})
                // Throwing an error, to be able handle errors later, in component.
                throw new Error(errorMessage)
            });
    }
}

现在,dispatch 函数正在 return 承诺:

handlerFunction {
  dispatch(doPost(data))
      // Now, we have access to `response` object, which we returned from promise in `doPost` action.
      .then(response => {
          // This function will be called when async action was succeeded.
          closeWindow();
      })
      .catch(() => {
          // This function will be called when async action was failed.
      });
}