I started using promises in angular for resolving my api calls with the following syntax:
$scope.module = moduleFactory.get({id: $stateParams.id})
.$promise.then(function(response){
$scope.module = response;
}
Now, I have encountered a situation where I have to chain multiple promises in a for loop and execute some code once all the promises in the for loop have been resolved. I have been trying to search for how to do this with the $promise syntax, but most sources on the internet talk about $q. I am new into development work and am finding it very confusing to juggle between these two concepts ($q and $promise). Request you nice folks to: first, explain to me the difference between $promise and $q; second, if I decide to use $q for solving my present problem as described above, does it mean I will have to rewrite the code that used $promise in order to make it chainable with something like $q.all()?
You can construct a promise in angular by calling $q:
let promise = $q(function(resolve, reject) { ... };
or if you simply want a promise that resolves immediately:
let promise = $q.resolve(somevalue);
There is also an older way using $q.defer() to construct a deferred object and returning it's .promise attribute, but you should probably avoid doing it that way and consider it just for backward compatibility.
The final way to create a new promise is to call .then() (or .catch()) on an existing promise.
The .$promise attribute is simply a promise created by one of the above mechanisms either by the $resource service or by something following the same pattern.
Once you have some promises you can stuff them all into an array and use $q.all() to wait for them all to complete, or for one to reject. Or if you want things to happen sequentially you can chain them together by performing each step in the .then() of the previous promise:
let promise = $q.resolve();
for(... something ...) {
promise = promise.then(() => { ... next step here ...});
}
promise.then(() => { ... runs when everything completed ...});
That will execute everything in sequence whereas $q.all() starts them off in parallel. Sometimes you want one, sometimes the other:
let promises = [];
for(... something ...) {
promises.push(somethingThatReturnsAPromise());
}
$q.all(promises).then(() => { ... runs when everything completed ...});
$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.
Related
I am not able to understand the use of $q service in angular js. Can some one please give elaboration on this topic that
what is the $q service in angularjs? How can we use that
I think article i wrote about $q might help you.
Introduction to $q
$q is an angular define a service. It’s same as new Promise(). But $q takes things to the next level by enhancing additional feature that developers can use to perform complex tasks more simply.
This is a sample for creating promise using $q
angular.module("app",[])
.controller("ctrl",function($scope,$q){
var work = "resolve";
var promise = $q(function(resolve, reject) {
if (work === "resolve") {
resolve('response 1!');
} else {
reject('Oops... something went wrong');
}
});
promise.then(function(data) {
alert(data)
})
})
$q.defer()
$q.defer() return the instance of the promise constructor. Once you create a defer object there are following methods and properties that you can access from that object
resolve(value) – resolves the derived promise with the value. If the value is a rejection constructed via $q.reject, the promise will be rejected instead.
reject(reason) – rejects the derived promise with the reason. This is equivalent to resolving it with a rejection constructed via $q.reject.
notify(value) - provides updates on the status of the promise's execution. This may be called multiple times before the promise is either resolved or rejected.
promise – {Promise} – promise object associated with this deferred
Conclusion
Use $q for constructing promises from non-promise Objects/callbacks, and utilize $q.all() and $q.race() to work with existing promises.
I have an Angular app, which contains a menu that is defined in av MVC view. So the menu is not related to the routes in the app. In the menu controller, I would like to inject an object containing data about the current user. I will then loop this object to decide which menu items should be visible to the user.
The factory looks like this:
.factory('currentUser', ['currentUserResource', function (currentUserResource) {return currentUserResource.get()}])
The get method is a standard $resource GET method.
Problem is, the factory returns a promise which takes a short while to resolve. So in my controller, some of the menu items are processed before the promise is resolved, and aren't showing when they should show.
In my controller I inject 'currentUser', and then have tried using in these ways:
$scope.currentUser = currentUser.then(function (data){
return data
});
$scope.currentUser = currentUser;
currentUser.then(function(data){
$scope.currentUser = data;
});
Is there any way, without using routing resolve, I can make sure that currentUser is resolved before the controller is loaded, or atleast that it is resolved first thing the controller does?
Use the $promise property of the $resource object to delay the work of the controller.
resourceObject.$promise.then ( function onFulfilled(object) {
//Do work that needs fulFilled object
}).catch (function onRejected(response) {
console.log(response.status)
});;
If the the resourceObject has been resolved, the onFulfilled function will be execute immediately. If the resourceObject has not been resolved, the $q service will wait before invoking the onFulfilled function.
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
I'm designing an API client with angular and the $http service using a Hypermedia API. Since I have resources that build on top of each other I wanted the client user to be able to do this declaratively:
apiRoot
.getPeopleRoot()
.getPerson(1)
.addJob(apiRoot.getJobsRoot().getRandomJob())
.updatePerson()
But I want to also be able to tap in $then methods to use intermediate results:
$scope.job = apiRoot.getJobsRoot().getRandomJob()
apiRoot.getPeopleRoot().getPerson(1).then(function (person) {
$scope.person = person
}).addJob($scope.job).updatePerson()
I managed to do each one of these separately by returning the promise or an object that contains the functions to operate with each of these resouces but I'm not sure how to achieve both at the same time, or if it's a good idea.
EDIT: I managed to progress using the following mixin to my resource objects
function Actualizable() {}
Actualizable.prototype.actual = function (value) {
this.realizedValue = value
return this
}
Then checking if I've resolved the value on each function or calling a promise to actually resolve it. I'm not sure if there's a mechanism to do this with promises still.
To chain promises, return values (or another promise).
apiRoot.getPeopleRoot().getPerson(1).then(function (person) {
$scope.person = person;
//return the value to chain
return person;
})
Because calling the .then method of a promise returns a new derived promise, it is easily possible to create a chain of promises
It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain.
-- AngularJS $q Service API Reference -- Chaining Promises
Also see Angular execution order with $q
What is the difference between defer object promise and promise from $resource service?
I know, that in some cases one uses $q service to create deferer, then resolve response and return promise.
Others in the same time might do something like return $resource(...).get().$promise;.
What is the diff. between those two approaches?
The promise returned from $resource is one someone initially used $q.defer() (or the newer more modern promise constructor) to create.
That someone is the $http service used internally inside $resource - you are using a promise they created for you.
Typically, you only need to use a $q.defer or the promise constructor at the lowest level of your code when working with async - otherwise you're typically better off using promise chaining. Otherwise you end up with the explicit construction anti-pattern.
I posted an issue on the AngularJS github but it doesn't seem to be getting a whole lot of attention and I wasn't able to fix it myself since it's a pretty low-level issue, so I think it's time to look for a workaround.
Angular allows you to put a promise (or anything with a .then(...) function) into your scope, and once it is resolved, all $watches and anything bound to that promise will use the resolved value. The issue arises when you use a function to return a promise, as the same doesn't apply - it's handled like a plain object.
For example:
var helloDef = $.Deferred();
$scope.hello = helloDef.promise();
$scope.getHello = function() {
return $scope.hello;
};
$timeout(function() {
helloDef.resolve('Hello!');
}, 1000);
Fiddle
Here using ng-bind="hello" works fine and outputs Hello!, but ng-bind="getHello()" outputs [object Object] as the internal $watch returns the promise object. Works the same way with $q instead of $.Deferred.
In my actual code I'm creating the promise the first time the function is called, so I can't just pre-make the promise and refer to that in scope.
I also need it for more than just ng-bind, so making my own binding directive which handles this case properly isn't viable.
Anyone have any ideas? I'm currently returning the promise if the data hasn't resolved and the actual result if it has, but that's a pain to work with. Anything bound to the data briefly causes weird side effects as the data is being loaded, like ngRepeat using the promise object instead of the resolved value to create elements.
Thanks.
UPDATE: Pull request: https://github.com/angular/angular.js/pull/3605
UPDATE 2: For future reference, automatic promise unwrapping has been deprecated in the 1.2 brach.
For some things, I use $resource. If I need to wait for it, $then works well:
var r = $resource...get...
var p = r.$then...
Otherwise, I build my own resource-like object that is not a promise, but has a promise that I can wait for.
Pull request merged, it should be fixed in 1.2.0 so I'll mark this as the answer.