【问题标题】:Redux thunk: return promise from dispatched actionRedux thunk:从分派的动作返回承诺
【发布时间】:2016-11-14 18:10:05
【问题描述】:

是否可以从动作创建者返回承诺/信号,当 Redux thunk 成功调度某些动作时解决?

考虑这个动作创建者:

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 或 POST_ERROR 动作时,我想在调用 doPost 动作创建者之后异步调用组件中的某些函数。一种解决方案是将回调传递给动作创建者本身,但这会使代码混乱且难以掌握和维护。我也可以在 while 循环中轮询 Redux 状态,但这会效率低下。

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

handlerFunction {
  doPost(data)
  closeWindow()
}

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

【问题讨论】:

    标签: javascript html reactjs redux redux-thunk


    【解决方案1】:

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

    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 函数正在返回一个承诺:

    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.
          });
    }
    

    【讨论】:

    • 我能否确保在 handlerFunction 之前调用 then 内部动作创建者?
    • 是的。 handlerFunction 中的代码将始终在 dispatch 代码之后调用。
    • 另外,由于某种原因,示例返回内部调度的 Action 对象而不是响应
    • 如果你想在调度异步操作后处理响应,你应该从.then函数返回response。您可以查看更新的答案以获取更多信息。
    猜你喜欢
    • 2018-12-28
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 2017-10-15
    • 2019-09-22
    • 2020-03-23
    • 2019-04-18
    相关资源
    最近更新 更多