Redux thunk:从分派动作返回Promise

IT技术 javascript html reactjs redux redux-thunk
2021-05-20 05:55:57

是否可以从动作创建者返回Promise/信号,在 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 状态,但这效率很低。

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

handlerFunction {
  doPost(data)
  closeWindow()
}

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

1个回答

当然,您可以从异步操作返回Promise:

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

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