Home:ALL Converter>Proper way of dealing with multiple promises in Angular

Proper way of dealing with multiple promises in Angular

Ask Time:2014-03-19T16:12:35         Author:Jon Snow

Json Formatter

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

Author:Jon Snow,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/22499787/proper-way-of-dealing-with-multiple-promises-in-angular
yy