Asynchronous Data Handling in AngularJs

Asynchronous is great in terms of performance, resource utilization and system throughput. Handling control flow is really painful. In Jquery and AngularJs we have promises to handle asynchronous requests.

A promise represents the eventual result of an operation. You can use a promise to specify what to do when an operation eventually succeeds or fails.

Promises in AngularJS are provided by the built-in $q service.

How it looks in Client-side:  
          
$http is one of the service that returns promise which contains the response.
var promise = $http.get("/api/my/name"); 
promise.success(function(name) { 
   console.log("Your name is: " + name);
});
promise.error(function(response, status) { 
   console.log("The request failed with response " + response + " and status code " + status);
});


How it looks in Server-side:

Promises in AngularJS are provided by the built-in $q service.
function respond(name) {

  var deferred = $q.defer();

  setTimeout(function() {
    deferred.notify('About to greet ' + name + '.');
 
    if (okToGreet(name)) {
      deferred.resolve('Hello, ' + name + '!');
 
    } else {
      deferred.reject('Greeting ' + name + ' is not allowed.');
    }
  }, 1000);
 
  return deferred.promise;
}

Deferred Object
·        A deferred object is simply an object that exposes a promise as well as the associated methods for resolving that promise.
·        It is constructed using the $q.deferred() function.
·        Exposes three main methods: resolve(), reject(), and notify(). 

resolve()

Called to send success response with message, only after process completes.

reject()

Called to send failure response with message, only after process completes.

notify()

Called to send intermediate response with message, while processing.
http://jsfiddle.net/jsengel/8fzmqy4y/

Using the $q Constructor to create a promise

  return $q(function(resolve, reject) {
      $timeout(function() {
        if(Math.round(Math.random())) {
          resolve('data received!')
        } else {
          reject('oh no an error! try again')
        }
      }, 2000)
    })  
}
}
Under the hood, AngularJS actually wires up a promise for an HTTP request in a way a bit like this:
var request = new XMLHttpRequest();  
request.addEventListener("load", function() {  
  // complete the promise
}, false);
request.addEventListener("error", function() {  
  // fail the promise
}, false);
request.open("GET", "/api/my/name", true);  
request.send();  


Comments