AngularJS Promise : notify example

A simple example using $timeout to notify the caller of our promise

by Yonathan Benitah

HTML

<div ng-app>
  <div ng-controller="PromiseCtrl">
      {{result}} ({{notify}})
  </div>
</div>

JavaScript

function PromiseCtrl($scope, $q, $timeout) {
    // Our promise function with its delay as argument
    var getPromise = function(delay) {
    console.log("start");
        // Creates a Deferred object
        var deferred = $q.defer();
        // Number of notifications sent
        var notifications = 0;
        
        // For each second in the delay, we will notify the caller
        for (var i = 0; i <= delay / 1000; i++) {
            setTimeout(function() {
                deferred.notify(notifications++);
            }, i * 1000);
        }
        
        // Always resolve the promise when the delay is reached        
        $timeout(function() {
            deferred.resolve("Success");
        }, delay);
        
        // The promise of the deferred task
        return deferred.promise;
    };
    
    // Creates a promise that will last 10 seconds
    getPromise(10000).then(function(value) {
        $scope.result = value; // Success callback
    },null, function(value) {
        $scope.result = "Waiting";
        $scope.notify = value; // Notify callback called each second
    });
}