Srik
Srik

Reputation: 2381

angularjs multiple $http promise in a function

I have a function where I make multiple $http.get calls. I want the function to wait until all the calls are complete. Below is the scenario

myApp.run(['$httpBackend','$http',function($httpBackend, $http){
    $http.get('data1.json').then(function(data){
        //do something
    });
    $http.get('data2.json').then(function(data){
        //do something
    });
    $http.get('data3.json').then(function(data){
        //do something
    });

    //return the function only after all three .then functions are compelte
}]);

I am using promise, however I am not sure I am using it in a right way. Right now the function .run() returns even before the $http.get().then() calls are complete.

Upvotes: 0

Views: 784

Answers (2)

Srik
Srik

Reputation: 2381

I was able to achieve my goal by injecting a factory as dependency to the run method.

Factory method where all the json files are retrieved:

myApp.factory('getJsons', ['$resource', function ($resource) {
    var data1 = $resource('data1.json').get();
    var data2 = $resource('data2.json').get();
    var data3 = $resource('data3.json').get();
    return {
        data1 : data1,
        data2 : data2,
        data3: data3
    };
}]); 

The modified run method

myApp.run(['$httpBackend','$http', 'getJsons', 
    function($httpBackend, $http, getJsons){
    //do something with getJsons.data1

    //do something with getJsons.data2

    //do something with getJsons.data3

    //The function is returned  only after all three jsons are processed
}]);

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

You can use $q and chain them all:

myApp.run(['$httpBackend','$http', '$q', function($httpBackend, $http, $q) {
    $q.all([
        (function() {
            var d = q.defer();
            $http.get('data1.json').then(function(data){
                d.resolve(data);
            });
            return d.promise;
        })(),
        (function() {
            var d = q.defer();
            $http.get('data2.json').then(function(data){
                d.resolve(data);
            });
            return d.promise;
        })(),
        (function() {
            var d = q.defer();
            $http.get('data3.json').then(function(data){
                d.resolve(data);
            });
            return d.promise;
        })()
    ]).then(function(responses) {
        console.log(responses); //array of your responses
    });
}]);

Upvotes: 2

Related Questions