what-wg를 사용하는 응용 프로그램에서 작업하고 있습니다.약속 체인에 대한 대체 캐치를 정의 하시겠습니까?
fetch('/api/specific/route', fetchDefaults)
.then(fetchMiddleware)
.then(function(data) {
// ... Dispatch case-specific fetch outcome
dispatch(specificRouteResponseReceived(data));
});
우리는 모든 fetch
에 일반, 대체 캐치를 추가 할 :
export function fetchMiddleware(response) {
return new Promise(resolve => {
resolve(checkStatus(response));
}).then(parseJSON);
}
export const fetchDefaults = {
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
우리는 우리의 기본 미들웨어를 사용/옵션이 방법을 가져 오기 : 우리는 기본 미들웨어 및 옵션이 방법을 가져 정의한 이 같은 다른 단어 뭔가, 응용 프로그램 전반에 걸쳐을 용도 : 코드 중복의
export function fetchGenericCatch(function(error) {
showGenericErrorFlashMessage();
})
fetch('/en/api/user/me/preferences', fetchDefaults)
.then(fetchMiddleware)
.then(function(data) {
dispatch(userPreferencesReceived(data));
})
.catch(fetchGenericCatch);
많이. 이 모든 작업을 수행 할 수있는 유틸리티 함수/클래스가 필요합니다 (예 : 같이 일하는 것이 뭔가 :
genericFetch('/api/specific/route') // bakes in fetchDefaults and fetchMiddleware and fetchGenericCatch
.then(function(data) {
dispatch(userPreferencesReceived(data));
}); // gets generic failure handler for free
genericFetch('/api/specific/route') // bakes in fetchDefaults and fetchMiddleware and fetchGenericCatch
.then(function(data) {
dispatch(userPreferencesReceived(data));
})
.catch(function(error) {
// ...
}); // short-circuits generic error handler with case-specific error handler
주요주의해야 할 점은 일반 catch
이 경우 특정 then
S/catch
ES 후 를 체인해야한다는 것입니다.
whatwg-fetch/ES6 Promises를 사용하여 어떻게 달성 할 수 있을지에 대한 정보가 필요하십니까?
관련 :
이 유사한 게시물이 있지만, 그들은 모두 기본값이 아닌 then
의 후 및 catch
ES 실행되는 기본 잡기의 필요성 해결하지 않는 것 :
-
을
- How to create a Promise with default catch and then handlers
- Default behavior if no other functions chained to a promise
편집 : 14 시월
가능한 중복 : Promises and generic .catch() statements
함수가 반환 된 후에 사용자가'.then/.catch'es를 추가하더라도 자동으로'.catch' 리스너를 추가하겠다는 점을 이해하고 있습니까? AFAIK는 불가능합니다. – nils
아니요, 캐치되지 않은 오류를 처리 할 기본 약속 인'catch'를 추가하고 싶습니다. 오류가 적용될 수 있다면 --- 캐치 처리기가 정의되지 않았다면 말입니다. –