EN RU

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”

1
2
3
4
5
6
7
$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

1
2
3
4
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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

1
2
3
4
5
6
7
8
var promises = [];
$scope.cats.forEach(function(cat){
    promises.push(cat.$update());
});

$q.all(promises).then(function(){
    // do something after all http requests
});
    2015-01-30 10:00:40      javascript angularjs