Tomarto
Tomarto

Reputation: 2755

jQuery's "$.when().done()" for AngularJS

I was looking for some way to know when two or more ajax calls have finished using AngularJS but I was only able to find it using jQuery:

$.when(promise3, promise5).done(
    function(threeSquare, fiveSquare) {
        console.info(threeSquare, fiveSquare);
    }
);

and:

var promises = [
    $.getJSON('square/2'),
    $.getJSON('square/3'),
    $.getJSON('square/4'),
    $.getJSON('square/5')
];

$.when.apply($, promises).done(function() {
    console.info(arguments);
});

is there any way to do something like this using AngularJS? Thanks for your support!

Upvotes: 3

Views: 4266

Answers (1)

Brian Lewis
Brian Lewis

Reputation: 5729

You will want to look at $q.all(); You can read about it here.

Here is a snippet:

all (promises)

Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

Parameters promises – {Array.} – An array of promises. Returns {Promise} – Returns a single promise that will be resolved with an array of values, each value corresponding to the promise at the same index in the promises array. If any of the promises is resolved with a rejection, this resulting promise will be resolved with the same rejection.

In version 1.1.x, you should be able to do something like this:

$q.all([
    $http.get('square/2'),
    $http.get('square/3'),
    $http.get('square/4'),
    $http.get('square/5')
]).then( function(arrayOfResponses) {
    $log.info('all set');
    $log.debug(arrayOfResponses);
});

Update:

As of version 1.1.6, you should be able to do the following:

var Square = $resource('square/:id', {id:1});
$q.all([
    Square.get({id:2}).$promise,
    Square.get({id:3}).$promise,
    Square.get({id:4}).$promise,
    Square.get({id:5}).$promise
]).then(function(arrayOfResponses) {
    $log.info('all set');
    $log.debug(arrayOfResponses);
});

Upvotes: 9

Related Questions