Promises in AngularJS in ES6 style

Posted By : Milind Ahuja | 26-Sep-2017

ECMAScript 6 gives us an alternative mechanism which is built into the language and is called a Promise. It is same as the callback functions but with better syntx and easy error handling.

Promise in ES6 is a constructor that takes an executer function that can resolved and reject promises. Angular updated its promise API with ECMAScript 6 standards, but onliny partly as not all the methods are supported yet. But what has been changed is that $q can be used as a constructor now.

So instead of creating an deffered like this: 

function myFunctionThatReturnsAPromise() {
  var deferred = $q.defer();

  anAsyncFunction(function (success) {
    deferred.resolve(success);
  }, function (error) {
    deferred.reject(error);
  });

  return deferred.promise;
}

myFunctionThatReturnsAPromise().then(yay, nay);

 

Promise constructor API can be used and return it directly without first creating a deferred object :

function myFunctionThatReturnsAPromise() {
  return $q(function (resolve, reject) {
    anAsyncFunction(function (success) {
      resolve(success);
    }, function (error) {
      reject(error);
    });
  });
}

 

By doing this we can definitely save the lines of code which was needed to create a deferred object first and it also makes the code more reusable for the future. So we don't have to change our code with $q.defer to work with promises at all as this the small addition rather than the replacement in the new version of Angular that will not affect the code.

 

THANKS

About Author

Author Image
Milind Ahuja

Milind is a bright Lead Frontend Developer and have knowledge of HTML, CSS, JavaScript, AngularJS, Angular 2+ Versions and photoshop. His hobbies are learning new computer techniques, fitness and interest in different languages.

Request for Proposal

Name is required

Comment is required

Sending message..