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

ngResource로 정의 된 단일 공장이 있습니다.

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
    };
});

jQuery의 $ .when (). then () 기능과 유사하게 ngResource로 정의 된 AngularJS 팩토리로이를 수행하는 방법이 있습니까? 현재 프로젝트에 jQuery를 추가하고 싶지 않습니다.



답변

promises 및 $ q.all () 을 사용하고 싶을 것 입니다.

기본적으로 $ resource 또는 $ http 호출이 promise를 반환하기 때문에 모든 $ 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의 솔루션이 최고이지만 완전하지는 않습니다. 오류 조건을 처리해야하는 경우 (예, 그렇습니다) 다음 catch과 같이 promise 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메서드가 실행되지 않으므로 인터페이스가 잘못된 상태로 남게됩니다.


답변