Chapter 8: Chaining promises and promise handlers

HTML

<script src="https://code.angularjs.org/1.3.2/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="Ctrl">
        <button ng-click="newAsyncNotification()">newAsyncNotification</button>
    </div>
</div>

JavaScript

angular.module('myApp', [])
.controller('Ctrl', function ($scope, $q, $log) {
    var deferred = $q.defer()
    , promise = deferred.promise;
    
    promise
    .then(
        function() {
            $log.log('success');
        },
        null,
        $log.log
    );
    
    $scope.newAsyncNotification = function() {
        setTimeout(function() {
            deferred.notify('Hello, ');
            $scope.$apply();
            $log.log('world!');
            deferred.resolve();
        });
    };
    
    // this function is invoked by some non-AngularJS entity
    // newAsyncNotification(); 
    // Hello, 
    // world! 
    // success
    
});