Sunday, May 15, 2016

angularjs too many request queue using promise

angularjs дээр олон тооны request илгээхдээ хүсэлт очиж байгааг дараалийг удирдаж дэс дараалалтай яаж илгээх вэ?

<div ng-app>
  <h2>$q test</h2>
  <div ng-controller="TodoCtrl">
      <div ng-bind="'Promise1: ' + Promise1"></div>
      <div ng-bind="'Promise2: ' + Promise2"></div>
      <div ng-bind="'Promise3: ' + Promise3"></div>
      <div ng-bind="'Promise4: ' + Promise4"></div>
      <div ng-bind="'Promise5: ' + Promise5"></div><br />
      <div ng-bind="'Status1: ' + Status1"></div>
      <div ng-bind="'Status2: ' + Status2"></div>
  </div>

</div>

JS:

function TodoCtrl($scope, $q, $timeout) {
    function createPromise(name, timeout, willSucceed) {
        $scope[name] = 'Running';
        var deferred = $q.defer();
        $timeout(function() {
            if (willSucceed) {
                $scope[name] = 'Completed';
                deferred.resolve(name);
            } else {
                $scope[name] = 'Failed';
                deferred.reject(name);
            }
        }, timeout * 1000);
        return deferred.promise;
    }
    
    // Create 5 promises
    var promises = [];
    var names = [];
    for (var i = 1; i <= 5; i++) {
        var willSucceed = true;
        if (i == 2) willSucceed = false;
        promises.push(createPromise('Promise' + i, i, willSucceed));
    }
    
    // Wait for all promises    
    $scope.Status1 = 'Waiting';
    $scope.Status2 = 'Waiting';
    $q.all(promises).then(
        function() { 
            $scope.Status1 = 'Done'; 
        }, 
        function() { 
            $scope.Status1 = 'Failed'; 
        }
    ).finally(function() {
        $scope.Status2 = 'Done waiting';
    });
}

result:

Promise1: Completed
Promise2: Failed
Promise3: Completed
Promise4: Completed
Promise5: Completed

Status1: Failed
Status2: Done waiting

No comments: