A promise is an interface that deals with objects that are returned or get filled in at a future point in time ( Basically, asynchronous actions ). At its core, A promise is an object with a then function.
AngularJS has introduced Promise API to handle this scenario.
var bloggerProfile = null; var userLogin = 'youvcode'; fetchServerContext( function (serverConfig) { fetchBloggerProfiles( BlogConfig.BLOGGER_PROFILES, userLogin, function(profiles){ bloggerProfile = profiles.bloggerProfile; }); });
There are few difficulties while using above approach:
- You need to encapsulate the business logic with bloggerProfile in the innermost callback, either directly or through a another function.
- Errors reported in between callbacks and functions have a tendency to be lost unless you handle them manually at every step of the function calls.
- Reluctant code is an indentation nightmare, especially when you have nested calls.
Promises solve all above issues:
var userLogin = 'yoUVcode'; var bloggerProfile = fetchServerContext().then(function(blogConfig) { return fetchBloggerProfiles(BlogConfig.BLOGGER_PROFILES, userLogin); }).then(function(profiles){ return profiles.blogProfile; }, function (errorInfo) { // Handle error scenarios here });
This will help you to deal with above 3 difficulties.
- Chaining of function will help you to get rid of indentation nightmare
- this will ensure that once first call will finish then only second will start executing
- Each then function can take 2 arguments(functions), first one is success callback and another is error handler.
.then( successCallbackFunction, failureCallbackFunction)
- When errors occurs in the chain, the error will get propagated through to the rest of the error handlers. So any error in any of the callbacks can be handled at the end.
In angular, to handle the promise it is having inbuilt service $q
$q.resolve(data) — Fulfill the promise and calls the success handler function
$q.reject(data) — it fails the service and it calls the error handlers.
Main purpose of using Promises with angularJS:
- It is widely used while calling AJAX service calls
- It is used when you are dealing with complex calculations which take lots of time
You can find more details on AngularJS site.