Angular $q.when Demonstration

by Željko Szep

HTML

<div ng-app="myApp">
    <div>{{status1}}</div>
    <div>{{status2}}</div>
</div>

JavaScript

(function () {
    var app = angular.module("myApp", []);
    app.service('noPromise', function () {
        return {
            getResult: function () {
                return {
                    status: "noPromise"
                };
            }
        };
    });
    app.service("promise", ['$q', '$timeout', function ($q, $timeout) {
        return {
            getResult: function () {
                var deferral = $q.defer();
                $timeout(function () {
                    deferral.resolve({
                        status: "promise"
                    });
                }, 1000);
                return deferral.promise;
            }
        };
    }]);
    app.run(['$rootScope', '$q', 'noPromise', 'promise',

    function ($rootScope, $q, noPromise, promise) {
        $rootScope.status1 = 'Ready.';
        $rootScope.status2 = 'Ready.';
        $q.when(noPromise.getResult()).then(function (result) {
            $rootScope.status1 = result.status;
        });
        $q.when(promise.getResult()).then(function (result) {
            $rootScope.status2 = result.status;
        });
    }]);
})();