Waiting for Finishing Asynchronous Calls in AngularJS

Here I’ll try to describe a few ways of waiting for asynchronous calls finish in AngularJS, from simplest to more complicated.

Simplest option from documentation about $http

When we use $http service, we can set two methods which will call only after http request, “success” and “error”

$http.get('/')
    .success(function(data, status, header, config){
        console.log('SUCCESS', data, status, header, config);
    })
    .error(function(data, status, header, config){
        console.log('ERROR', data, status, header, config);
    })

Do something after load, using ngResource

Just add call of method of $promise - then

Cat.get({name: 'Barsik'})
    .$promise.then(function(cat){
        console.log('AFTER GET CAT', cat);
    })

Waiting for a couple of calls (not http).

Here we can use defer/promise from service $q.

var deferred = $q.defer();
var promise = deferred.promise
promise.then(function(){
    //...
});
promise.then(function(){
    //...
});

deferred.resolve();

Waiting for a couple of http requests

Here we need $q service too. We should collect all promises of $http to the list and then using $q.all wait for all of them finish

var promises = [];
$scope.cats.forEach(function(cat){
    promises.push(cat.$update());
});

$q.all(promises).then(function(){
    // do something after all http requests
});