AngularJS – Deferred & Promise

Playing around AngularJS. I didn’t know that AngularJS has deferred/promise functionality, which may be mostly known as jQuery feature.

The following is a simple example to wait for the completion of multiple tasks which takes random time.

http://jsfiddle.net/7svNT/

<!doctype html>
<html ng-app="Promise">
<head>
  <meta charset="UTF-8">
  <script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
  <script src="http://code.angularjs.org/1.1.5/angular-resource.min.js"></script>

  <title>Promise Test</title>
  <script>
    var app = angular.module('Promise', []);

    function PromiseCtrl($scope, $q) {
      $scope.run = function() {
        $scope.items = [];
        var promises = [];

        for(var i = 0; i < 5; i++) {
          var time = Math.floor(Math.random() * 10 + 5) * 500;
          $scope.items.push({time: time, css: ""});

          var promise = waitTask(time, i);
          promise.then(function(index) {
            $scope.items[index].css = "completed";
          });
          promises.push(promise);
        };

        $q.all(promises).then(function(messages) {
          $scope.message = "All " + messages.length + " tasks completed.";
        });
      }

      function waitTask(time, index) {
        var deferred = $q.defer();

        setTimeout(function() {
          $scope.$apply(function() {
            deferred.resolve(index);
          });
        }, time);

        return deferred.promise;
      }
    }

  </script>

  <style>
    .box {
      border: solid 1px;
      width: 100px;
      padding: 10px;
      margin: 10px;
    }

    .completed {
      background: #88dd88;
    }
  </style>
</head>
<body>
  <div ng-controller="PromiseCtrl">
    <a href="#" ng-click="run()">Start</a><br/>

    <div ng-repeat="item in items track by $index" ng-class="item.css" class="box">
      {{item.time}} msec
    </div>

    <div>{{message}}</div>
  </div>
</body>
</html>
Advertisements

Posted on May 29, 2013, in JavaScript. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: