Chapter 8: Chaining promises and promise handlers

by billy roberts

HTML

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

JavaScript

//var newPromise = $q.when(123); with $apply

angular.module('myApp', [])
.controller('Ctrl', function ($scope, $q, $log) {
    setTimeout(function() {
        var newPromise = $q.when(123);
        
        // promise will wait for a $digest cycle to update $$state.status,
        // this forces it to update for inspection
        $scope.$apply();
        
        // inspecting the status reveals it has already resolved
        $log.log(newPromise.$$state.status);
        // 1
        
        // since it is resolved, the handler will execute immediately
        newPromise.then($log.log);
        // 123
    });
});