Redux thunk:从派遣行动中返回承诺

Tuo*_*nen 7 html javascript reactjs redux redux-thunk

是否可以从动作创建者返回promise/signal,当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})
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

handlerFunction {
  doPost(data)
  closeWindow()
}
Run Code Online (Sandbox Code Playgroud)

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

1ve*_*ven 8

当然,你可以从异步动作返回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)
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,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.
      });
}
Run Code Online (Sandbox Code Playgroud)

  • 是.`handlerFunction`中的代码将始终在`dispatch`代码之后调用. (2认同)