Last Updated: September 27, 2021
·
17.01K
· gerardsans

Angular - Promises basics ($q service for $http)

AngularJs Meetup South London Collection | this article

Angular promises

While using Angular and generally when using JavaScript in a middle sized project you will find yourself dealing with a lot of callback functions and/or asynchronous calls to retrieve data from the backend.
To keep things smooth promises come to our rescue.

In this protip I will provide a basic skeleton to get started with angular $q service so you will know how to approach promises.

Features shown in this protip:

- promise basic infrastructure
- basic promise usage with $http
- advanced scenario using promises with $http

Promise introduction

1) Create deferred object

The deferred object controls the state of the promise. We can trigger three resolutions: resolve, reject and notify. In the following steps we will see how it relates to the promise setup.

This is how you create a deferred object:

var deferred = $q.defer();

2) Setup Promise

In order to use the deferred object we need to setup the promise handlers before. This will be the code executed for each situation. The scenarios are: success, failure and progress notification. The promise object is a property of the deferred object.

var promise = deferred.promise;

//basic version
promise.then(fnSuccess)
  .catch(fnFailure) //optional
  .finally(fnAlways) //optional

//advanced version
promise.then(fnSuccess, fnFailure, fnNotification)
  .catch(fnFailure) //optional
  .finally(fnAlways) //optional

3) Deferred resolution

Once we have created the deferred object and setup the promise, we can execute our asynchronous processing and trigger the promise with the final resolution.

deferred.resolve(resultObj); //triggers fnSuccess
deferred.reject(reasonObj); //triggers fnFailure
deferred.notify(progressObj); //triggers fnNotification 

Basic $http promise usage

This example uses a promise returned by a get $http call.

$http.get('movies.json')
.then(function(response){
   $scope.movies= response.data;
})
.catch(function(response){
  console.log(response.status);
});

plunker

Advanced $http promise usage

This example uses promises to handle $http calls behind a Service. More complex handling can be added to the Service afterwards.

app.factory("Movies", function($http, $q) {
  return {
    get: function() {
        var deferred = $q.defer();
        $http.get('movies.json')
        .then(function(response){
           deferred.resolve(response.data);
        })
        .catch(function(response){
          deferred.reject(response);
        });
        return deferred.promise;
    }
  }
})
...
app.controller("MoviesCtrl", function($scope, Movies) {
   Movies.get().then(function(data){
      $scope.movies = data;
   })
   .catch(function(response){
      console.log(response.status);
   }); 
})
...

plunker

Resources

Angular $q service is inspired by the q library.

$q service, $http service

AngularJs Meetup South London Collection | this article

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

Angular apps often share the page with analytics and payment scripts that are not Angular modules. Those scripts execute on the same origin as the framework.

Security insights from Cside