首页 > 解决方案 > 如何使用 redux-thunk 和 try-catch 处理多个调度结果?

问题描述

我正在使用 redux-thunk 进行操作调用和减速器返回状态。我的操作本质上是对后端的 axios API 请求。对于一个特定的操作,我需要按照代码中显示的确切顺序调度一组事件:

  1. 检查tokenvalue用户传递的是否有效(对 tokencollection 有自己的 axios api 请求)。如果 1. 失败,跳转到 catch 块。
  2. 如果令牌确实有效,请使用 axios post 注册用户。如果 2. 失败,跳转到 catch 块
  3. 如果用户注册成功,将令牌设置给用户(因此每个用户只有一个唯一令牌)。如果 3. 失败,跳转到 catch 块。

为了按上述顺序依次实现它们,我将它们放在 try-catch 块中。结果证明我对工作原理的理解dispatch是错误的——如果调度因错误而失败,它仍会执行后续调度。关于如何解决这个问题的任何建议?:

export const register = ({name,email,password,tokenval}) => async(dispatch) =>{
try{
    await dispatch(checkTokenValidity(tokenval)); // if this fails, jump to catch block
    const res = await axios.post("/api/users", body, config); //if this fails jump to catch
    await dispatch(setUserToToken({ tokenval, userID: res.data.userID })); //if this fails jump to catch
    dispatch({
      type: REGISTER_SUCCESS,
      payload: res.data,
    });
}catch(err){
  dispatch({
      type: REGISTER_FAIL,
    });
}
};

标签: reactjspromisereact-reduxredux-thunk

解决方案


  • 确保 checkTokenValidity 在失败时抛出错误。有了这个,它会自动去 catch 块
  • 无需使用调度和等待令牌有效性
  • 将 api 结果存储在变量中并进行必要的检查并相应地调度操作。

您重构的代码

export const register = ({ name, email, password, tokenval }) => async (
  dispatch
) => {
  try {
    const isValidToken = await checkTokenValidity(tokenval); // no need of dispatch - just make sure that the checkTokenValidity throws an error upon fail
    if(!isValidToken ){
        throw new Error('server error - invalid token')
    }
    const usersResult = await axios.post("/api/users", body, config); //if this fails jump to catch
    if(!usersResult ){
        throw new Error('server error - usersResult')
    }
    const setUserToTokenResults = await dispatch(setUserToToken({ tokenval, userID: res.data.userID })); //if this fails jump to catch
    if(!setUserToTokenResults ){
        throw new Error('server error - setUserToTokenResults')
    }
    dispatch({
      type: REGISTER_SUCCESS,
      payload: res.data,
    });
  } catch (err) {
    dispatch({
      type: REGISTER_FAIL,
      payload: {err} //<---- provide some error message to the reducer
    });
  }
};

推荐阅读