javascript / react / redux async等待重构

时间:2017-11-07 15:38:43

标签: javascript reactjs promise async-await refactoring

我想重构fetchRelationships函数以使用async await。我不确定最好的方法是什么,因为此代码在.then包含嵌套response.json().then((json) =>...

可以发布重构版本吗?

export const fetchRelationshipsError = (error) => {
  return {
    type: FETCH_RELATIONSHIPS_FAILURE,
    payload: { error }
  };
};

export const fetchRelationshipsRequest = () => {
  return { type: FETCH_RELATIONSHIPS_REQUEST };
};

export const fetchRelationshipsSuccess = (relationships) => {
  return {
    type: FETCH_RELATIONSHIPS_SUCCESS,
    payload: relationships
  };
};

export const fetchRelationships = (url) => {
  return (dispatch) => {
    dispatch(fetchRelationshipsRequest());

    fetch(url, config)
    .then((response) => {
      const responseObj = {
        response: response,
        payload: response.json().then((json) => {
          return { body: json }
        })
      };

      if (!response.ok) {
        const error = new Error(response.statusText);
        responseObj.payload.then((response) => {
          show_error_alert(response.body);
          dispatch(fetchRelationshipsError(response.body));
        });
        throw error;
      }

      return responseObj.payload;
    })
    .then((response) => {
      dispatch(fetchRelationshipsSuccess(response.body))
    })
    .catch((error) => { console.log('Request failed', error); });
  };
};

解决方案:

export const fetchRelationships = (url) => {
  return async (dispatch) => {
    dispatch(fetchRelationshipsRequest());

    try {
      const response = await fetch(url, config);
      const jsonResponse = await response.json();

      if (!response.ok) {
        show_error_alert(jsonResponse);
        dispatch(fetchRelationshipsError(jsonResponse));

        const error = new Error(response.statusText);
        throw error;
      }

      dispatch(fetchRelationshipsSuccess(jsonResponse));

    } catch(error) {
      console.log('Request failed', error);
    }
  };
};

1 个答案:

答案 0 :(得分:2)

我会抓住这个:

export const fetchRelationshipsError = (error) => {
  return {
    type: FETCH_RELATIONSHIPS_FAILURE,
    payload: { error }
  };
};

export const fetchRelationshipsRequest = () => {
  return { type: FETCH_RELATIONSHIPS_REQUEST };
};

export const fetchRelationshipsSuccess = (relationships) => {
  return {
    type: FETCH_RELATIONSHIPS_SUCCESS,
    payload: relationships
  };
};

export const fetchRelationships = (url) => {
  return async (dispatch) => {

    dispatch(fetchRelationshipsRequest());

    try{

      const response = await fetch(url, config)
      const jsonResponse = await response.json()

      if(!response.ok){

        show_error_alert(jsonResponse);
        dispatch(fetchRelationshipsError(jsonResponse));

        const error = new Error(response.statusText);
        throw error;
      }

      dispatch(fetchRelationshipsSuccess(jsonResponse));

    }catch(error){
      console.log('Request failed', error);
    }  

  };