1

//inside a service PService

this.getPTypes = function(){
        var types = PTypesFactory.get({});
        return types.$promise.then(function(result)
        {
            console.log(result.groups);
            return result.groups;
        });
    }

//inside a controller

$scope.groups = PService.getPTypes();

console log shows correct fetched REST data, but when I do

console.log($scope.groups);

I get

Object {then: function, catch: function, finally: function}

which is promise API instead of the correct resolved data.

2 Answers 2

1

The problem is that you trying to use a asynchronous function like it was a synchronous one.

then is a method which returns a promise.

when invoking it with a callback that callback would not be invoked immediately, only when the response get back from the server.

You can write it like so:

Service

this.getPTypes = function(callback){
  PTypesFactory.get({}).then(callback);
}

Controller

PService.getPTypes(function(res){
  $scope.groups = res.data;
});
Sign up to request clarification or add additional context in comments.

Comments

0

Promises are used to handle asynchronous operations. The function you pass to the then method is called at some indeterminable point in time. You can't return a value from within it to some other point in execution.

Instead of calling then in your service, just return the promise:

this.getPTypes = function(){
    return PTypesFactory.get({}).$promise;
}

and handle its resolution in the controller:

$scope.groups = PService.getPTypes().then(function(result) {
    console.log(result.groups);
});

2 Comments

moving the .then function to controller doesnt affect the output, its the same as mentioned in Question
@user494461 - Do you even need the then? Return $promise from the service and do $scope.groups = PService.getPTypes();.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.