Handling Catch in Thunk Action with async/await

陌路散爱 提交于 2019-12-24 10:57:49

问题


Having trouble figuring out how to handle exceptions here.

Container

  async handleResetPassword(uuid) {
        console.log("handleResetPassword invoked!")
        try {
          await this.props.resetUserPassword()
    ...rest of the code

Thunk Action

export function resetPasssord() {
  return async (dispatch, getState) => {
    const state = getState()

    try {
      const response = await UserApi.ResetUserPassword(state.auth.token)

      if(response && response.body){
        dispatch(UserActions.resetPasswordReceived)
      }

      dispatch(UserActions.resetPasswordFail)
    }
    catch(err) {
      //what do I do here?  How should I resolve this?
      dispatch(UserActions.resetPasswordFail)
    }
  }
}

Also how to handle the related API's catch. As you see above the thunk action calls the Api here:

UserApi (uses superagent):

const ResetUserPassword = async (token) => {
  try{
    return await request
      .post(`${endpoint}/users/recover-password`)
      .set({ Authorization: `Bearer ${token}` })
      .accept('application/json')
  }
  catch(err) {
    console.log(err)
    //how handle this?
  }
}

Here are my thoughts when brainstorming this:

  • need to return some kind of promise from API call in catch so that await can resolve in thunk action
  • need to return some kind of promise from thunk action in catch so that container can resolve the rejection
  • do I dispatch an action for error in the try-catch?

but I'm not sure if I'm on the right path or what to code in each of those catches above.

来源:https://stackoverflow.com/questions/45173331/handling-catch-in-thunk-action-with-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!