Combining two http requests into one promise

Computer code on the screen

As developers we often find ourselves doing things we shouldn’t be doing, and putting best practices aside for the sake of a “solution.” In my case I found myself needing data that was not in our API end point, because it was customized to suit another application’s needs. So I had to make another API call to get another piece of data. I initially tried nesting call 2 inside of of call 1’s promise, and it worked for what I needed to do, however that is too much stop and go traffic. So in comes $q.all grabs your two requests in an array $q.all([promise1, promise2]), and then chain your .then(function(response){}) of the requests. Once resolved you data comes back in an array [0] or [1] to do with what you please.

app.factory("fetch_data", ['$http', '$q',  function($http, $q){
    var deferred = $q.defer();
    return {
        getData: function(){
            var promise1 = $http({method: 'GET', url: "/this/url/one", cache: 'true'}),
                promise2 = $http({method: 'GET', url: "/this/url/two", cache: 'true'});
            $q.all([promise1, promise2]).then(function(response){
                deferred.resolve({channel: response[0].data,vendor: response[1].data});
            },
            function(data) {
                deferred.resolve({channel: dummyData});
            });
            return deferred.promise;
        }
    }
}]);

I am mostly writing this for myself, as I know I will surely come back to this necessity once again, but also for anyone who may be looking for the solution to a double API call in Angular JS. Let me know if you have a way to improve it. I am always looking for critique, and other ways to do things.

Published
Categorized as Code