Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - wait for multiple resource queries to complete

Tags:

angularjs

I have a single factory defined with ngResource:

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

I am making multiple calls to the query method defined on this factory. The calls can happen asynchronously, but I need to wait for both calls to complete before continuing:

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

Is there a way to do this with AngularJS factories defined with ngResource, similar to jQuery's $.when().then() functionality? I would prefer not to add jQuery to my current project.

like image 425
Nathan Donze Avatar asked Mar 08 '13 17:03

Nathan Donze


2 Answers

You'll want to use promises and $q.all().

Basically, you can use it to wrap all of your $resource or $http calls because they return promises.

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... }); 
like image 82
Ben Lesh Avatar answered Sep 24 '22 00:09

Ben Lesh


I think a better solution is:

$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... }); 
like image 25
Tales Mundim Andrade Porto Avatar answered Sep 23 '22 00:09

Tales Mundim Andrade Porto