-2
fetchRelationships
함수가 비동기 대기를 사용하도록 리팩토링하고 싶습니다. 이 코드가 중첩 된 .then
(response.json().then((json) =>...
)을 포함하고 있기 때문에 가장 좋은 방법은 무엇인지 모르겠습니다.javascript/react/redux async 리팩토링 대기
리팩토링 된 버전을 게시 할 수 있습니까?
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 초 편집합니다. 리턴 기능 (디스패치)의 비동기 기능을 추가했습니다. –
스펜서 (Spencer), 귀하의 아이디어를 기반으로 해결했습니다. 내 질문에 대한 해결책을 추가했습니다. 당신의 코드에는 여분의'async'를 포함한 몇 가지 실수가 포함되어 있습니다. 내 솔루션에 따라 변경 한 경우 귀하의 답변을 수락합니다. –