用户aync-await在react-redux thunk中

时间:2019-04-19 10:00:39

标签: reactjs redux async-await react-redux redux-thunk

我是react-redux的新手。在这里,我尝试使用aysnc-await。我在componentDidMount上拥有的是我正在调用的api,如果我在那里200 Ok,则只有我想调用第二个api。所以我为此使用async-await

export function fetchUserResumes(pageNo, jdId) {
  pageNo = 0;
  let size = 20;
  return (dispatch) => {
    const page = `page=${pageNo}`;
    let url = FETCH_RESUMES + '/' + jdId + '?' + page + '&' + size;
    dispatch({
      type: REQUEST_INITIATED
    })
    return get(url)
      .then((response) => {
        if (response.status === 200) {
          dispatch({
            type: FETCHING_RESUME_SUCCESS,
            data: response.payload
          })
          dispatch({
            type: REQUEST_SUCCESSED
          })
        } else {
          if (!response.status) {
            toastr.error('Our server is down. Please check again');
          }
          else if (response.status.status === 401) {
            dispatch(logout());
          }
          else if (response.status.status === 500) {
            toastr.error("Error while fetching Job description,Please try again");
            dispatch({
              type: FETCHING_RESUME_FAILED,
              data: response.status,
            });
            dispatch({
              type: REQUEST_SUCCESSED
            })
          } else {
            dispatch({
              type: REQUEST_SUCCESSED
            })
          }
        }
        return true;
      })
  }
};

在didmout上被调用的动作是

export function getUserJobInfo(jobId) {
  return async (dispatch) => {
    dispatch({
      type: REQUEST_INITIATED
    });
    let url = GET_JOB_INFO_URL + jobId;
    let response = await get(url);
    if (response.status === 200) {
      let pageNo = 0;
      let size = 20;
      const page = `page=${pageNo}`;
      let url = FETCH_RESUMES + '/' + jobId + '?' + page + '&' + size;
      let newApiResponse = await get(dispatch(fetchUserResumes(pageNo, jobId)));
      dispatch({
        type: USER_JOB_INFO,
        data: response.payload
      })
    }
    else {
    }
  }
}

这是我尝试执行此操作的方法。但是这里我在使用async await时非常困惑,所以任何人都可以帮我解决这个问题。 谢谢。

1 个答案:

答案 0 :(得分:0)

您无需在get上致电await get(dispatch(fetchUserResumes(pageNo, jobId)));

在重击的情况下,dispatch返回的内容与返回内部函数的内容相同。因此,在您的情况下,此调度的返回类型将为Promiseawait可以满足任何承诺。

  let newApiResponse = await dispatch(fetchUserResumes(pageNo, jobId));