$promise
is a property of objects returned by the $resource Service class-type action methods.
It is important to realize that invoking a $resource
object method immediately returns an empty reference (object or array depending on isArray
). Once the data is returned from the server the existing reference is populated with the actual data.
The Resource instances and collections have these additional properties:
$promise
: the promise of the original server interaction that created this instance or collection.
On success, the promise is resolved with the same resource instance or collection object, updated with data from server. This makes it easy to use in resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.
On failure, the promise is rejected with the http response object, without the resource property.
--AngularJS $resource Service API Reference
Note: The example code in the question is redundant and unnecessary.
$scope.module = moduleFactory.get({id: $stateParams.id})
.$promise.then(function(response){
//REDUNDANT, not necessary
//$scope.module = response;
});
The assignment of resolved responses to $scope is not necesssary as the $resource will automatically populate the reference when the results come from the server. Use the $promise property only when code needs to work with results after they come from the server.
To distinguish services which return $resource Service objects from other services which return promises, look for a .then
method. If the object has a .then
method, it is a promise. If it has a $promise
property, it follows the ngResource pattern.
It must be obvious to you, but I used an array of $resource.$promise's inside $q.all() and it worked.
$q.all works with promises from any source. Under the hood, it uses $q.when to convert values or promises (any then-able object) to $q Service promises.
What sets $q.all apart from the all
method in other promise libraries is that in addition to working with arrays, it works with JavaScript objects that have properties that are promises. One can make a hash (associative array) of promises and use $q.all to resolve it.
var resourceArray = resourceService.query(example);
var hashPromise = resourceArray.$promise.then(function(rArray) {
promiseHash = {};
angular.forEach(rArray,function (r) {
var item = resourceService.get(r.itemName);
promiseHash[r.itemName] = item.$promise;
});
//RETURN q.all promise to chain
return $q.all(promiseHash);
});
hashPromise.then(function (itemHash) {
console.log(itemHash);
//Do more work here
});
The above example creates a hash of items indexed by itemName with all the items being fetched asynchronously from a $resource Service.
$promise
is a property on the return value of certain operations which returns a promise for the result of that operation.$q
is a service which provides some promise creation and manipulation mechanisms like$q.all
and$q.resolve
. – Simonize