1

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.

TMN
  • 3,060
  • 21
  • 23
  • Looks like this is only part of the code. There is also at least one bracket missing after the second `then()`. Why do you need the immediately invoked function? Can you post the code in context? What is exactly returned from the server (literally)? Where do you output the values to the console? – lex82 Jan 22 '16 at 09:24
  • Yeah, the actual code is about fifty lines and has a bunch of unrelated stuff, I tried to pare it down and genericize it to more clearly explain the structure. I need the IIFE because otherwise It creates a closure in the loop and I only get results for the last element in the list. I edited the example to show where the logging is done. – TMN Jan 22 '16 at 13:39
  • If this is the real code that means `XService` uses a custom, flawed implementation of promises. – Tamas Hegedus Jan 22 '16 at 13:51

1 Answers1

1

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.

Community
  • 1
  • 1
lex82
  • 11,173
  • 2
  • 44
  • 69