programing

AngularJS - 여러 리소스 쿼리가 완료될 때까지 기다립니다.

kingscode 2023. 3. 12. 12:39
반응형

AngularJS - 여러 리소스 쿼리가 완료될 때까지 기다립니다.

ngResource를 사용하여 정의된 팩토리가 1개 있습니다.

App.factory('Account', function($resource) {
    return $resource('url', {}, {
        query: { method: 'GET' }
    });
});

이 공장에서 정의된 쿼리 메서드로 여러 번 호출합니다.콜은 비동기적으로 발생할 수 있습니다만, 계속 진행하기 전에 양쪽 콜이 완료될 때까지 기다릴 필요가 있습니다.

App.controller('AccountsCtrl', function ($scope, Account) {
    $scope.loadAccounts = function () {
        var billingAccounts = Account.query({ type: 'billing' });
        var shippingAccounts = Account.query({ type: 'shipping' });

        // wait for both calls to complete before returning
    };
});

Angular로 할 수 있는 방법이 있나요?jS 팩토리는 ngResource로 정의되며 jQuery의 $.when() 기능과 유사합니다.현재 프로젝트에 jQuery를 추가하고 싶지 않습니다.

약속과 $q.all()을 사용합니다.

기본적으로 $resource 또는 $http 콜은 약속을 반환하기 때문에 모든 $resource 또는 $http 콜을 래핑할 수 있습니다.

function doQuery(type) {
   var d = $q.defer();
   var result = Account.query({ type: type }, function() {
        d.resolve(result);
   });
   return d.promise;
}

$q.all([
   doQuery('billing'),
   doQuery('shipping')
]).then(function(data) {
   var billingAccounts = data[0];
   var shippingAccounts = data[1];

   //TODO: something...
});

더 나은 해결책은 다음과 같습니다.

$q.all([
   Account.query({ type: 'billing' }).$promise,
   Account.query({ type: 'shipping' }).$promise
]).then(function(data) {
   var billingAccounts = data[0];
   var shippingAccounts = data[1];

   //TODO: something...
});

Ben Lesh의 솔루션은 최고이지만 완전하지는 않습니다.에러 상태를 처리할 필요가 있는 경우(네, 있습니다),catchPromise API의 메서드는 다음과 같습니다.

$q.all([
   doQuery('billing'),
   doQuery('shipping')
]).then(function(data) {
   var billingAccounts = data[0];
   var shippingAccounts = data[1];

   //TODO: something...

}).catch(function(data) {

   //TODO: handle the error conditions...

}).finally(function () {

  //TODO: do final clean up work, etc...

});

정의하지 않으면catch그리고 너의 모든 약속은 실패하면then메서드는 실행되지 않기 때문에 인터페이스가 불량 상태가 될 수 있습니다.

언급URL : https://stackoverflow.com/questions/15299850/angularjs-wait-for-multiple-resource-queries-to-complete

반응형