dotnethaggis
dotnethaggis

Reputation: 999

Angular - multiple promises wrapped in one promise

I have a couple of services that return the same type of objects just a different type via a flag on the object. These services have functions that return a promise.

Service 1 - getPlaces:

this.getPlaces = function () {
            return $http.get('http://somewhere.com').then(function (response) {
                    return response;
     }).catch(exception.catcher('Something went wrong'));
};

Service 2 - getPlaces:

this.getPlaces = function () {
            return $http.get('http://somewhere.com/').then(function (response) {
                    return response;
     }).catch(exception.catcher('Something went wrong'));
};

What I also have is a wrapper Service that calls both of these services and I don't want the function in the service wrapper to return the combined results until both promises fully executed and returned results (or null). I'm currently doing it the following way:

    this.getCombinedResults = function () {
        var combined= [];

        var apiCalls = [service1.getPlaces(), service2.getPlaces()];

        $q.all(apiCalls.map(function(call) {
            return call;
        })).then(function (response) {
            angular.forEach(response, function (item, index) {
                combined.push(item);
            });
        });            
        return combined;
    };

Is this the correct way of wrapping multiple promises in a promise? If not what should change. I don't think it's working correctly, particularly in my wrapper service. When calling the wrapper service function it returns null.

I'm going to look into this more but if I can get a heads up as to whether what I'm writing is correct would be great. Thanks.

Upvotes: 0

Views: 1036

Answers (1)

Chandermani
Chandermani

Reputation: 42669

Since the getCombinedResults is calling a promise based service, this service too should return a promise, else combined will always be empty.

Just do

 return $q.all(apiCalls.map(function(call) {
            return call;
        })).then(function (response) {
            angular.forEach(response, function (item, index) {
                combined.push(item);
            });
            return combined;
        }); 

Because then too returns a promise, this code will return a promise back to caller.

The resolved value would be combined.

Also in the calling code you need to use promise based resolution of response using then.

Upvotes: 2

Related Questions