小编典典

Redux重击:从已调度操作中返回承诺

reactjs

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()
}

上面的示例应该被重构,因此closeWindow()仅在doPost()成功时才被调用。


阅读 279

收藏
2020-07-22

共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.
      });
}
2020-07-22