Working with AngularJS promises

AngularJS is a Javascript single page application framework which is developed and maintained by Google. The AngularJS Promise is an object that represents the result of an asynchronous action, regardless of whether that action is still pending.

The great thing about Javascript and single page applications is that they work in an asynchronous way, which means that DOM elements and page layout can be changed instantly on the client side. The problem with asynchronous behavior is that most of the information that is being displayed, is pulled from the server, and this information takes some time to arrive.

AngularJS has a classic solution for this behavior.
The solution is to use the $q module. $q provides an interface called “promise”. A promise object is used for interacting with the result of an action that is performed asynchronously regardless of whether that action is still pending.

$q module has two major AngularJS instances. The first is “deferred” and the second is “Promise” (the result object).

Deferred Instance:

The purpose of the deferred object is to expose the associated Promise instance.

Promise Instance:

A new promise instance is created when a deferred instance is created.
The purpose of the promise object is to get access to the result object of the deferred task when it completes. This way you can make asynchronous tasks and obtain the result in an unknown point in time.

AngularJS promise

Simple Deferred/Promise example:

1. First lets create the deferred function which will return the promised object.

$scope.giveMePromise = function(email, password) {
// Init the deferred instance.
        var deferred = $q.defer();
// Set the Data, RequestedUrl and any other information.
        var endPoint = "/user/register/";
        var url = “https://www.panda-os.com/” + endPoint;
        var postData = {
            email: email,
            password: password
        }

        $http({
            method: 'POST',
            url: url,
            headers: {
                'Content-Type': 'application/json'
            },
            data: postData,
            cache: false
        }).
// Assign the success and error result to the the deferred instance.
            success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).
            error(function(data, status, headers, config) {
                deferred.reject(data);
            });

// Return the promised object.
        return deferred.promise;

    }

2. Lets use the deferred function and assign the result object to one of our $scope variables.

var email = “royc@panda-os.com”;
var password = “*******”;
$scope.giveMePromise(email, password).then(successCallback function(result) {
// Handle the success promise.
         $scope.user = result;
}, (errorCallback function(result) {
// Handle the error promise.
         console.log(“error:” + result);
});

The code above demonstrates a simple example of how to use the deferred/promise api of AngularJS. The beauty of the deferred technique is that you can easily create a chain of promises of any length, because a promise can be resolved with another promise which will defer its resolution further.

Chain promise example.

1. First lets use the function from step 1 in the above example.
2. Lets create the chain…

var email = "royc@panda-os.com";
var password = “*******”;
var promiseA = $scope.giveMePromise(email, password);
$scope.promiseB = promiseA.then(function(result) {
        result.addData = "I want to change the promise and add to it information";
        return result;
})

The above code shows how $scope.promiseB is waiting for the promiseA result.

The complete flow is as follows:

1. promiseA is being executed – In this time $scope.promiseB is still waiting.
2. promiseA completed and then the second promise is being executed.
promiseA.then(function(result) – $scope.promiseB is still waiting.
3. The second promise finished and then $scope.promiseB is being assigned with the new data from both promises.

For more information about the $q module you can visit $q module and Q documentation

Leave a Reply

Your email address will not be published. Required fields are marked *