$q 약속 오류 콜백 체인
다음 코드 조각에서error 1그리고.success 2기록됩니다.원래 지연된 콜백이 거부된 경우 호출되는 오류 콜백을 호출하지 않고 호출되는 오류 콜백을 전파하려면 어떻게 해야 합니까?
angular.module("Foo", []);
angular
.module("Foo")
.controller("Bar", function ($q) {
var deferred = $q.defer();
deferred.reject();
deferred.promise
.then(
/*success*/function () { console.log("success 1"); },
/*error*/function () { console.log("error 1"); })
.then(
/*success*/function () { console.log("success 2"); },
/*error*/function () { console.log("error 2"); });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Foo">
<div ng-controller="Bar"></div>
</div>
오류는 반환함으로써 전파됩니다.$q.reject에러 콜백에서
var deferred = $q.defer();
deferred.reject();
deferred.promise
.then(
/*success*/function () { console.log("success 1"); },
/*error*/function () { console.log("error 1"); return $q.reject('error 1')})
.then(
/*success*/function () { console.log("success 2"); },
/*error*/function () { console.log("error 2"); });
});
성공을/ failure을 시도로 생각하다/
try{
var val = dummyPromise();
} catch (e){
val = "SomeValue";
}
catch가 예외를 만들지 않으면 오류가 처리된 것으로 간주되며 따라서 외부 호출 함수는 내부 함수에서 발생한 오류를 보지 못합니다.
여기서 비슷한 일이 일어나고 있어요, 당신은 돌아와야 합니다.return $q.reject();약속으로부터 다음 약속도 실패할 수 있도록 말입니다.플렁커 예제 참조: http://plnkr.co/edit/porOG8qVg2GkeddzVHu3?p=preview
그 이유는 오류 처리자가 오류를 수정하기 위한 조치를 취할 수 있기 때문입니다.오류를 처리하는 당신의 오류 기능에서, 만약 달리 명시되지 않았다면, 그것은 해결된 새로운 약속을 반환할 것입니다.따라서 기본적으로 다음 약속이 실패하는 것은 타당하지 않습니다(try-catch analysis).
그건 그렇고, 당신은 돌아올 수 있습니다.$q.reject()심지어 성공 처리자에게서도, 만일 당신이 오류 상태를 감지한다면, 연쇄 실패에서 다음 약속을 할 수 있습니다.오류를 파악하고 처리하면 성공 처리자에게 전달됩니다.거부하려면 $q.reject();를 반환해야 합니다.
의견을 요약하고 약속 체인의 오류를 전파하려면 다음 중 하나를 수행합니다.
1) 제공 안 함errorCallback위해서then:
deferred.promise
.then(
/*success*/function () { console.log("success 1"); },
.then(
/*success*/function () { console.log("success 2"); },
/*error*/function () { console.log("error 2"); }); // gets called
아니면
2) 반품$q.reject()로부터errorCallback:
deferred.promise
.then(
/*success*/function () { console.log("success 1"); },
/*error*/function (err) { console.log("error 1"); return $q.reject(err); });
.then(
/*success*/function () { console.log("success 2"); },
/*error*/function () { console.log("error 2"); }); // gets called
This api should be used to forward rejection in a chain of promises.
언급URL : https://stackoverflow.com/questions/26442199/q-promise-error-callback-chains
'programing' 카테고리의 다른 글
| 워드 프레스 페이지에서 "http"를 "https"로 모두 변경 (0) | 2023.09.26 |
|---|---|
| .prop('checked', false) 또는 .removeAtr('checked')? (0) | 2023.09.26 |
| parse csv 파일을 Maria DB로 가져오는 방법? (0) | 2023.09.26 |
| 도커 로그인 알 수 없는 속기 플래그: 'e' (0) | 2023.09.21 |
| 내장형 장치에 적합한 직렬 통신 프로토콜/스택? (0) | 2023.09.21 |