-2
fetchRelationships
関数を非同期待ちにすることをリファクタリングしたいと思います。私は、このコードがresponse.json().then((json) =>...
にネストされた.then
を含んでいるので、これを行うのが最善の方法であるかどうかはわかりません。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秒編集します。戻り関数の非同期追加(ディスパッチ) –
スペンサー、あなたのアイデアに基づいて解決しました。私は私の質問に解決策を追加しました。あなたのコードには、余分な 'async'を含むいくつかの間違いがあります。私の解決策に基づいてそれを変更した場合、私はあなたの答えを受け入れます。 –