programing

성공/오류/최종/각도로 약속 사용JS

lovejava 2023. 3. 15. 17:46

성공/오류/최종/각도로 약속 사용JS

사용하고 있다$httpAngularJs를 통해, 반환된 약속을 어떻게 사용해야 할지, 오류에 어떻게 대처해야 할지 잘 모르겠습니다.

코드는 다음과 같습니다.

$http
    .get(url)
    .success(function(data) {
        // Handle data
    })
    .error(function(data, status) {
        // Handle HTTP error
    })
    .finally(function() {
        // Execute logic independent of success/error
    })
    .catch(function(error) {
        // Catch and handle exceptions from success/error/finally functions
    });

이게 좋은 방법일까요, 아니면 더 쉬운 방법이 있을까요?

약속은 우리가 비동기 코드로 동시에 우리 자신을 표현할 수 있게 해주는 진술에 대한 추상화입니다.이는 일회성 태스크의 실행을 나타냅니다.

또한 일반 코드와 마찬가지로 약속에서 돌아오거나 던질 수 있는 예외 처리도 제공합니다.

동기 코드로 필요한 것은 다음과 같습니다.

try{
  try{
      var res = $http.getSync("url");
      res = someProcessingOf(res);
  } catch (e) {
      console.log("Got an error!",e);
      throw e; // rethrow to not marked as handled
  }
  // do more stuff with res
} catch (e){
     // handle errors in processing or in error.
}

프로미스 버전은 매우 유사합니다.

$http.get("url").
then(someProcessingOf).
catch(function(e){
   console.log("got an error in initial processing",e);
   throw e; // rethrow to not marked as handled, 
            // in $q it's better to `return $q.reject(e)` here
}).then(function(res){
    // do more stuff
}).catch(function(e){
    // handle errors in processing or in error.
});

사용하는 것을 잊다success그리고.error방법.

두 방법 모두 각도 1.4에서는 사용되지 않습니다.기본적으로, 이러한 권위의 배후에 있는 것은, 말하자면 체인 친화적이지 않기 때문입니다.

다음 예에서는 다음 예에 대해 설명하겠습니다.success그리고.error체인에 친화적이지 않습니다.주소를 가진 사용자 개체를 반환하는 API를 호출한다고 가정합니다.

사용자 개체:

{name: 'Igor', address: 'San Francisco'}

API 호출:

$http.get('/user')
    .success(function (user) {
        return user.address;   <---  
    })                            |  // you might expect that 'obj' is equal to the
    .then(function (obj) {   ------  // address of the user, but it is NOT

        console.log(obj); // -> {name: 'Igor', address: 'San Francisco'}
    });
};

무슨 일입니까?

왜냐면success그리고.error원래의 약속, 즉 돌아온 약속을 되돌리다$http.get오브젝트는 의 콜백에 전달됩니다.then사용자 객체 전체를 말합니다.즉, 앞의 입력과 같은 입력입니다.success콜백

만약 우리가 2개를 묶었다면then이 경우 혼란을 줄일 수 있습니다.

$http.get('/user')
    .then(function (user) {
        return user.address;  
    })
    .then(function (obj) {  
        console.log(obj); // -> 'San Francisco'
    });
};

앞의 답변은 맞다고 생각합니다만, 여기 또 다른 예가 있습니다(각도에 따라 f.y.i, success() 및 error()만 권장되지 않습니다).JS 기본 페이지:

$http
    .get('http://someendpoint/maybe/returns/JSON')
    .then(function(response) {
        return response.data;
    }).catch(function(e) {
        console.log('Error: ', e);
        throw e;
    }).finally(function() {
        console.log('This finally block');
    });

어떤 종류의 세분화를 원하십니까?일반적으로 다음과 같은 방법으로 해결할 수 있습니다.

$http.get(url).then(
  //success function
  function(results) {
    //do something w/results.data
  },
  //error function
  function(err) {
    //handle error
  }
);

여러 약속을 묶을 때 "드디어"와 "잡기"가 더 낫다는 것을 알게 되었습니다.

Angular $http의 경우 success() 및 error() 함수는 응답 오브젝트를 언랩하기 때문에 콜백시그니처는 $http(...).success(function(data, status, headers, config)와 같습니다.

raw response object를 다루게 될 것입니다.Angular에 게시된 것과 같은JS $http API 문서

$http({
        url: $scope.url,
        method: $scope.method,
        cache: $templateCache
    })
    .success(function(data, status) {
        $scope.status = status;
        $scope.data = data;
    })
    .error(function(data, status) {
        $scope.data = data || 'Request failed';
        $scope.status = status;
    });

이전 약속 체인에서 새로운 오류가 발생하지 않는 한 마지막 .catch(...)는 필요하지 않습니다.

브래들리 브라이스웨이트가 블로그에서 제안한 것처럼요.

app
    .factory('searchService', ['$q', '$http', function($q, $http) {
        var service = {};

        service.search = function search(query) {
            // We make use of Angular's $q library to create the deferred instance
            var deferred = $q.defer();

            $http
                .get('http://localhost/v1?=q' + query)
                .success(function(data) {
                    // The promise is resolved once the HTTP call is successful.
                    deferred.resolve(data);
                })
                .error(function(reason) {
                    // The promise is rejected if there is an error with the HTTP call.
                    deferred.reject(reason);
                });

            // The promise is returned to the caller
            return deferred.promise;
        };

        return service;
    }])
    .controller('SearchController', ['$scope', 'searchService', function($scope, searchService) {
        // The search service returns a promise API
        searchService
            .search($scope.query)
            .then(function(data) {
                // This is set when the promise is resolved.
                $scope.results = data;
            })
            .catch(function(reason) {
                // This is set in the event of an error.
                $scope.error = 'There has been an error: ' + reason;
            });
    }])

요점:

  • 해결 함수는 컨트롤러의 .the function에 링크되어 있습니다.즉, 모든 것이 정상이기 때문에 약속을 지키고 해결할 수 있습니다.

  • Reject 함수는 컨트롤러의 .catch 함수에 링크되어 있습니다.즉, 뭔가 잘못되었기 때문에 약속을 지킬 수 없기 때문에 거부할 필요가 있습니다.

하며, 하는 다른 에서 데이터를 호출할 수 .deferred.reject(anotherReason)거절당한 이유와 함께요

Ryan Vice가 코멘트에서 제안했듯이, 예를 들어 답변을 조금만 조작하지 않으면 유용하게 보이지 않을 수 있습니다.

★★★★★★★★★★★★★★★★★★success ★★★★★★★★★★★★★★★★★」error1인 약속 1.4를 수 .일반적인 약속 방법을 사용하는 것이 좋을 수 있습니다.then ★★★★★★★★★★★★★★★★★」catch이러한 메서드 내에서 응답을 변환하고 변환된 응답의 약속을 반환합니다.

두 가지 접근법과 세 번째 접근법 모두에서 동일한 예를 보여 줍니다.

success ★★★★★★★★★★★★★★★★★」error접근)success ★★★★★★★★★★★★★★★★★」error응답의 합니다.$q"이러한 정보":

function search(query) {
  // We make use of Angular's $q library to create the deferred instance
  var deferred = $q.defer();

  $http.get('http://localhost/v1?=q' + query)
  .success(function(data,status) {
    // The promise is resolved once the HTTP call is successful.
    deferred.resolve(data);              
  })

  .error(function(reason,status) {
    // The promise is rejected if there is an error with the HTTP call.
    if(reason.error){
      deferred.reject({text:reason.error, status:status});
    }else{
      //if we don't get any answers the proxy/api will probably be down
      deferred.reject({text:'whatever', status:500});
    }
  });

  // The promise is returned to the caller
  return deferred.promise;
};

then ★★★★★★★★★★★★★★★★★」catch접근(투구로 인해 테스트하기가 조금 더 어렵다):

function search(query) {

  var promise=$http.get('http://localhost/v1?=q' + query)

  .then(function (response) {
    // The promise is resolved once the HTTP call is successful.
    return response.data;
  },function(reason) {
    // The promise is rejected if there is an error with the HTTP call.
    if(reason.statusText){
      throw reason;
    }else{
      //if we don't get any answers the proxy/api will probably be down
      throw {statusText:'Call error', status:500};
    }

  });

  return promise;
}

중간 해결 ).throw, 어쨌든,은 아마 「아주머니」를 사용할 가 있을 입니다.$q"CHANGE: "CHANGE: "CHANGE: "CHANGE: "CHANGE: "CHANGE:")

function search(query) {
  // We make use of Angular's $q library to create the deferred instance
  var deferred = $q.defer();

  $http.get('http://localhost/v1?=q' + query)

  .then(function (response) {
    // The promise is resolved once the HTTP call is successful.
    deferred.resolve(response.data);
  },function(reason) {
    // The promise is rejected if there is an error with the HTTP call.
    if(reason.statusText){
      deferred.reject(reason);
    }else{
      //if we don't get any answers the proxy/api will probably be down
      deferred.reject({statusText:'Call error', status:500});
    }

  });

  // The promise is returned to the caller
  return deferred.promise;
}

어떠한 코멘트나 수정도 환영합니다.

언급URL : https://stackoverflow.com/questions/23559341/using-success-error-finally-catch-with-promises-in-angularjs