Kristiyan Kostadinov
Kristiyan Kostadinov

Reputation: 3712

Proper way of dealing with multiple promises in Angular

What is the proper way to fire a function after multiple $http requests have finished? I have 2 options but I'm not sure which is the proper one. Note that both log 'done', after 'one' and 'two' have completed.

First, I'm just pushing all the $http requests to an array and using $q.all(promises).then to fire the final callback, I don't remember where I saw this but it seems to be working fine(might be because my localhost is fast at processing the requests):

var one = $http.get("/request/one/"),
    two = $http.get("/request/two/"),
    promises;

    one.then(function(response){
        console.log('one');
    });

    two.then(function(response){
        console.log('two');
    });

    promises = $q.all([one, two]);

    promises.then(function(){
        console.log('done');
    });

Second, I've seen it in a few tutorials, including https://egghead.io/lessons/angularjs-q-all:

var one = $q.defer(),
    two = $q.defer(),
    promises;

    $http.get("/request/one/").then(function(response){
        one.resolve('one');
    });

    $http.get("/request/two/").then(function(response){
        two.resolve('two');
    });

    promises = $q.all([one.promise, two.promise]);

    promises.then(function(result){
        console.log('done');
    });

Upvotes: 1

Views: 124

Answers (1)

Anders Ekdahl
Anders Ekdahl

Reputation: 22933

You should definitely go with the first approach. The second one creates two unnecessary promises. $http already returns promises, so there's no need to create two more with $q.defer().

Upvotes: 2

Related Questions