Search code examples
javascriptangularjsngresource

How does ngResource attach a promise to an array


I'm trying to understand how ngResource in AngularJS is able to return an array but also allows you to append a .$promise on it to get the promise object.

Basically from the example below it looks like if you just call the query function you get an empty array back (that populates when the promise resolves).

However, it seems too that the return value has a $promise property that can be accessed. This is weird to me because I'm not sure how you can attach a promise to an array, just an object. There must be something about javascript that I'm missing here and maybe you can clarify.

e.g. from angular website:

// We can retrieve a collection from the server
var cards = CreditCard.query(function() {
  // GET: /user/123/card
  // server returns: [ {id:456, number:'1234', name:'Smith'} ];

but you can also access the raw $http promise using the $promise property:

var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123})
    .$promise.then(function(user) {
      $scope.user = user;
    });

Is angular able to give an array a $promise property somehow?


Solution

  • ngResource returns a empty Resource instance or Array instance for each method. Both instances are given the $promise and $resolved properties to be able to add promise calls or use the result directly in your $scope.

    If I remember correctly AngularJS used to look at these properties when you set this value on a $scope property.

    There are more libraries out there that give Array custom methods (like jQuery).

    ngResource source:

    return value:

    https://github.com/angular/bower-angular-resource/blob/master/angular-resource.js#L562

    promise added:

    https://github.com/angular/bower-angular-resource/blob/master/angular-resource.js#L637