Promises in an AngularJS

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:

  1. You need to encapsulate the business logic with bloggerProfile in the innermost callback, either directly or through a another function.
  2. 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.
  3. 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.

  1. Chaining of function will help you to get rid of indentation nightmare
  2. this will ensure that once first call will finish then only second will start executing
  3. Each then function can take 2 arguments(functions), first one is success callback and another is error handler.

        .then( successCallbackFunction, failureCallbackFunction)

  1. 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:

  1. It is widely used while calling AJAX service calls
  2. It is used when you are dealing with complex calculations which take lots of time

You can find more details on AngularJS site.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s