programing

$q 약속 오류 콜백 체인

subpage 2023. 9. 26. 22:21
반응형

$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

각진 $q.reject 설명서에서:

This api should be used to forward rejection in a chain of promises.

언급URL : https://stackoverflow.com/questions/26442199/q-promise-error-callback-chains

반응형