Search code examples
javascriptangularjsangular-promiseangular-resource

Promise resolution passes promise instead of value


I have a success callback set up on a value returned from a service, but when I reference the value it's a promise and not a simple type (boolean) like I expected. Here's the basic structure of the code:

var ZService = $resource('api/w/:id/zs'); // returns a list of Zs
var XService = $resource('api/x/:id/hasAttribute'); // returns a boolean value
$scope.zList = ZService.query({id:$scope.w.id});
$scope.zList.$promise.then(function(zs) {
    for(var i=0; i<zs.length; i++) {
        (function(i) {
            var z = zs[i];
            XService.get({id:z.x.id}).$promise.then(function(has) {
                console.log("has: " + has);
                z.attr = has;
            });
        })(i);
    }
}

In my view I'm using <span ng-show="z.attr == true"> (within a z in zList repeater) and that span never displays. If I log the value of has to the console, it shows that it's a promise, and not a boolean like I expect. Likewise, if I examine the value of z.attr in the debugger, it's an object (a resolved promise).

I've used promises in other places in my code and haven't had a problem, but most of the time I've assigned the return value to a variable within $scope, so I'm wondering if there's some kind of magic going on behind the scenes. In those other places I'm returning composite objects and not simple values, so I'm also wondering if that has something to do with it.


Solution

  • The problem is that $resource expects an object or an array of objects. It does not work with primitive values. When it retrieves an object, it adds convenience methods, such as $save which would not be possible otherwise.

    See this answer to a related question for details.