I’m new to Angular. This means that almost every day I’m slapped in the face with something amazing. Something that not only fixes my current development problem, but causes me to re-think how I’ve handled a ton of problems in the past. Today’s thing? Promises.

I started out with a simple Angular service. One of it’s returned functions posted data to an API endpoint:

factory('apiPost', function($http, $log) {
  return {
    dataPost: function(data) {
      $http.put('/path/to/api/', data).success(function() {
        $log.info("Yay");
      }).error(function() {
        $log.error("Boo");
      });
    }
  }
}

This worked fine, but as you can see in the success/error callbacks, I’m just logging output to the console. I wanted to call specific functions on error or success that tied into the app directly. I could have added the func calls in place of the above logs, but then the service wasn’t very reusable.

Promises to the Rescue

I asked someone smarter than me, and it turns out Angular promises do exactly what I needed.

factory('apiPost', function($http, $q) {
  return {
    dataPost: function(data) {
      var deferred = $q.defer();

      $http.put('/path/to/api/', data).success(function() {
        deferred.resolve();
      }).error(function() {
        deferred.reject();
      });

      return deferred.promise;
    }
  }
}

Here’s what’s happening here: First, I’m injecting Angular’s $q service. I won’t go into deep details on this, as the documentation is pretty extensive on the subject.

For my success/error handling above, I first added a deferred object via $q.defer() and stored it in a variable. This exposed the Promise instance and API for use later.

Now that I had access to the Promise API, I could reject or resolve that promise based on the status of my API request. Finally, I could return said promise for use later.

Why this is Awesome

Now that my promise was returning when I used the apiPost service, I used the then() function, passing a success callback function. That callback was where I could tie the service into any other parts of the app I wanted.

You can also pass a callback on failure and notify occurrences; I just passed a success callback:

apiPost.dataPost($scope.data).then(function() {
  // Do something awesome
});

This is great! My service is completely reusable, with callback functions I can attach if I need it to do different things in different places on success/failure.

Mind = blown.

I’m by no means an expert on this, and I highly recommend reading the Angular documentation. I’d love any feedback you guys have on the subject!

Scouts Honor icon designed by SPJDR from the Noun Project