Program Tip

Angular의 $ q.reject () 대 deferred.reject ()

programtip 2020. 11. 21. 09:23
반응형

Angular의 $ q.reject () 대 deferred.reject ()


Angular $q서비스와 관련 개체 및 API 에 대한 핸들을 얻으려고합니다 . 콘솔에서 개체를 보면 다음과 같은 내용이 표시됩니다.

var deferred = $q.defer()

...(and then from console inspection)...

$q: Object {defer: function, reject: function, when: function, all: function}

deferred: Object {resolve: function, reject: function, notify: function, promise: Object}

deferred.promise: Object {then: function, catch: function, finally: function}

몇 가지 질문이 제기됩니다.

  1. $q.reject()의 차이점은 무엇입니까 deferred.reject()? 각각을 언제 사용합니까?
  2. 사이의 관계를 무엇 errorFndeferred.promise.then(successFn, errorFn)catchFn있는가 deferred.promise.catch(catchFn)?
  3. 여러 개의 중첩 된 약속이 있고 오류가 발생하면 가장 바깥 쪽 catch()함수가 항상 호출됩니까? 중첩 된 promise 중 하나에 catch 함수가 정의되어 있으면 어떻게됩니까? 그 캐치가 가장 바깥 쪽 캐치가 실행되는 것을 방지합니까?

감사.


1) $q.reject()지연을 생성 한 다음 즉시 거부하는 단축키입니다. 오류를 처리 할 수 ​​없으면 errorFn에서 자주 사용합니다.

2) 아무것도, 서비스 의 성공 및 오류 메서드와 마찬가지로에 promise.catch(errorFn)대한 구문 설탕 promise.then(null, errorFn)일 뿐이 $http므로 다음과 같은 코드를 작성할 수 있습니다.

promise.
    then(function(result){
        // handle success
        return result;
    }, function errorHandler1(error){
        // handle error, exactly as if this was a separate catch in the chain.

    }).catch(function errorHandler2(error){
        // handle errors from errorHandler1
    });

3) 바로 $ q.reject가 유용 할 수있는 곳입니다 :

promise.
    catch(function(error){
       //Decide you can't handle the error
       return $q.reject(error); //This forwards the error to the next error handler;
    }).catch(function(error){
       // Here you may handle the error or reject it again.
       return 'An error occurred'; 
       //Now other errorFn in the promise chain won't be called, 
       // but the successFn calls will.
    }).catch(function(error){
       // This will never be called because the previous catch handles all errors.
    }).then(function(result){
       //This will always be called with either the result of promise if it was successful, or 
       //'An error occured' if it wasn't
    });

Ok 이것은 약속에서 얻은 것입니다.

  1. $q.reject(reason)인수로 전달되고 지연된 이유와 함께 거부 된 약속을 반환합니다. 거부는 프로세스가 완료되었는지 여부에 관계없이 지연된 존재를 거부합니다.

  2. errorFnPromise가 거부 될 때 시작되고 그 인수가 거부 된 이유입니다. Promise 프로세스 내의 오류가 제대로 처리되지 않아 Promise가 발생하고 예외가 발생하고 거부되거나 이행되지 않을 때 Catch가 호출됩니다.

  3. You shoudn't have nested promises, you should have chained promises in which case the latest catch block should catch everything prior to it if no other block was specified to handle it.

참고URL : https://stackoverflow.com/questions/24443733/angulars-q-reject-vs-deferred-reject

반응형