Q. What is a promise?

A promise in the Javascript and AngularJS world is an assurance that we will get a result (no matter success or fail) from an action at some point in the future. Two possible results of a promise

  • A promise is said to be fulfilled when we get a result from that action
  • A promise is said to be rejected when we don’t get a response

Using Angular’s $q service to deal with promises

Q.Angular's $q service

Angular JS provides a service called $q that helps you run functions asynchronously

$q constructor in CommonJS-style usage

A new instance of deferred is constructed by calling $q.defer().

var deferred = $q.defer();

The deferred object

Methods

  • resolve(value) - success with value
  • reject(reason) - fail with reason
  • notify(value) - notify

Properties

  • promise – {Promise} - promise object associated with this deferred.
The promise object

Methods

  • then(successCallback, [errorCallback], [notifyCallback])

Q. Put in all Exmaples

Have a look at a simple example

// deferred contains the promise to be returned
var deferred = $q.defer();

// to resolve (fulfill) a promise use .resolve
deferred.resolve(data);

// to reject a promise use .reject
deferred.reject(error);

How this would be implemented inside an AngularJS service

app.service("githubService", function ($http, $q) {

    var deferred = $q.defer();

    this.getAccount = function () {
        return $http.get('https://api.github.com/users/haroldrv')
            .then(function (response) {
                // promise is fulfilled
                deferred.resolve(response.data);
                // promise is returned
                return deferred.promise;
            }, function (response) {
                // the following line rejects the promise 
                deferred.reject(response);
                // promise is returned
                return deferred.promise;
            })
        ;
    };
});

How the AngularJS controller will use the service

app.controller("promiseController", function ($scope, $q, githubService) {



        .then(
            function (result) {
                // promise was fullfilled (regardless of outcome)
                // checks for information will be peformed here
                $scope.account = result;
            },
            function (error) {
                // handle errors here
                console.log(error.statusText);
            }
        );
});

results matching ""

    No results matching ""