2017-01-16 66 views
0

我有一個功能,根據用戶選擇的複選框檢索大量的數據。如果用戶選擇「全部」,則該功能使用鏈式承諾根據每個複選框的「id」獲取選定的數據。它在用戶首次選擇「全部」時完美運行。但是,如果用戶取消選擇「全部」,則再次選擇「全部」,鏈接的承諾不再鏈接。它走向第一個承諾,然後攤位。如果頁面刷新,鏈接的承諾將再次工作。下面的代碼只是提供「一般想法」的一個片段,因爲涉及到很多代碼。不知何故,似乎原來的承諾沒有被清除或什麼,但我不知道這個問題,因爲我沒有收到任何錯誤。AngularJS鏈接的承諾只能工作一次

當用戶點擊「全選」按鈕時調用此函數。

 $scope.selectAll = function() { 
    $scope.print.sections = angular.copy($scope.sections); 
    }; 

然後,當用戶點擊「打印所選」,下面的函數調用:

$scope.printSections = function() { 
    var promise = null; 
    $scope.print.sections.sort(setOrder); 
    $scope.dataLoading = true; 

      var cntr = 0; 
      var sections = $scope.print.sections; 
      function next() { 
       if (cntr < sections.length) { 
        promise = getSectionData(sections[cntr++]); 
        promise.then(next); 
       } 
      } 
      next(); 



    }; 

功能「getSectionData」通過它的「ID」獲得的數據每個部分。這不是這個函數的所有代碼,因爲它很長。

function getSectionData(section) { 
    var deferred; 
    deferred = $q.defer(); 
    var id = section.QuestionSectionID; 
    switch (id) { 
     case 1: 

      deferred.resolve(myService.getfirstSection(id) 
      .success(function (data) { 
       $scope.firstSection = data; 
      })); 

     break; 
    case 2: 
      deferred.resolve(myService.getSecondSection(id) 
      .success(function (data) { 
       $scope.secondSection= data; 
      })); 

     break; 
    } 
return deferred.promise; 
} 

問題是第二次,鏈接承諾的「next()」函數不起作用。 任何援助非常感謝!

回答

0

以下幾乎是您的代碼的副本,但沒有$q包裝爲Promise。我認爲唯一可能會丟失的是switch中的default選項在案例不匹配時發送空白承諾。

var cntr = 0; 
 
var sections = [1, 2, 989878, 3]; //data for 989878 does not exist 
 

 
function next() { 
 
    if (cntr < sections.length) { 
 
    promise = getSectionData(sections[cntr++]); 
 
    promise.then(next); 
 
    } 
 
} 
 
next(); 
 

 
function getSectionData(id) { 
 

 
    var deferred = null; 
 
    switch (id) { 
 
    case 1: 
 
     deferred = Promise.resolve(getOtherData(id).success(function(data) { 
 
     $('pre').append(JSON.stringify(data[0], {}, ' ')); 
 
     })); 
 
     break; 
 
    case 2: 
 
     deferred = Promise.resolve(getOtherData(id).success(function(data) { 
 
     $('pre').append(JSON.stringify(data[0], {}, ' ')); 
 
     })); 
 
     break; 
 
    case 3: 
 
     deferred = Promise.resolve(getOtherData(id).success(function(data) { 
 
     $('pre').append(JSON.stringify(data[0], {}, ' ')); 
 
     })) 
 
     break; 
 
    default: //return a default promise object. Comment the default out and see what happens 
 
     deferred = Promise.resolve(true); 
 
     break; 
 
    } 
 
    return deferred; 
 
} 
 

 
function getOtherData(id) { 
 
    return $.ajax({ 
 
    url: 'https://jsonplaceholder.typicode.com/users?id=' + id, 
 
    method: 'GET' 
 
    }); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<pre> 
 
    
 
</pre>