2017-07-25 89 views
0

如何在所有異步調用完成時停止函數? 我有誰遞增VAR槽一個異步調用或沒有(與if條件)的列表上的foreachAngularJs異步問題

我的代碼:

$scope.updateDureePeriodeList = function() { 

     var mttLoyer = 0 

     angular.forEach($scope.articleListDuree, function (value, key) { 
      if (value.selected) { 
       if (value.bOption) { 
        $scope.getTauxDevisRevOption(value.prixArt * value.qttArt).then(function (taux) { 
         mttLoyer += value.prixArt * value.qttArt * taux/100; 
        }) 
       } 
       else 
        mttLoyer += value.prixArt * value.qttArt * $scope.DureeEdit.taux/100; 
      } 

     }); 

     $scope.DureeEdit.periodeList = new Array(); 
     $scope.DureeEdit.periodeList.push({ 
      'numPeriode': 1, 
      'mttLoyer': parseFloat(mttLoyer).toFixed(2), 
     }); 
} 

問題:getTauxDevisRevOption是異步,當我進去吧,我功能不停止,因此做$scope.DureeEdit.periodeList.push在年底前mttLoyer是異步調用中。然後)增量(...

+2

搜索如何處理javascript中的異步操作 – Hitmands

+0

我已經完成了我的搜索並找到了答案,以處理帶有承諾的異步(即我調用getTauxDevisRevOption時執行的操作),但是在這種情況下,沒有找到答案,因爲我不能做的.then()所有的代碼,因爲我需要完成我的循環之前打電話給我在函數結束:/ – rob1

回答

1

接下來可以幫助你

function updateDureePeriodeList(data, defaultTaux, tauxLoader) { 

    return Promise 
    .all(
     Object 
     .keys(data) 
     .reduce((res, key) => { 
      const value = data[key]; 

      if(value.selected) { 
      const op = Promise 
       .resolve(value.bOption ? tauxLoader(value.prixArt * value.qttArt) : defaultTaux) 
       .then(taux => (value.prixArt * value.qttArt * taux/100)) 
      ; 

      res = res.concat(op); 
      } 

      return res; 
     }, []) 
    ) 
    .then(operations => operations.reduce((a, b) => a + b)) 
    ; 
} 

updateDureePeriodeList($scope.articleListDuree, $scope.DureeEdit.taux, (...args) => $scope.getTauxDevisRevOption(...args)) 
    .then(mttLoyer => console.log('mttLoyer', mttLoyer)) 
; 
+0

謝謝,我看你是如何處理這個!但是在angularJs中有相同的方法嗎? – rob1

+0

這是angularjs – Hitmands

+0

它的JavaScript,尋找$ q.all和我的解決方案更有棱角的接近,順便說一句,非常感謝你,你的回答讓我正確的方式無論如何! – rob1

0

鬆了一些頭髮後,我最終找到了我要求的解決方案! 使用$ q.all是關鍵。 我的工作代碼:

$scope.updateDureePeriodeList = function() { 
     var mttLoyer = 0 
     var allQ = []; 

     angular.forEach($scope.articleListDuree, function (value, key) { 
      if (value.selected) { 
       if (value.bOption) { 
        allQ.push($scope.getTauxDevisRevOption(value.prixArt * value.qttArt).then(function (taux) { 
         mttLoyer += value.prixArt * value.qttArt * taux/100; 
        })); 
       } 
       else 
        mttLoyer += value.prixArt * value.qttArt * $scope.DureeEdit.taux/100; 
      } 

     }); 

     $q.all(allQ).then(function(data){ 
      $scope.DureeEdit.periodeList = new Array(); 
      $scope.DureeEdit.periodeList.push({ 
       'numPeriode': 1, 
       'nbrEch': nbrEch, 
       'mttLoyer': parseFloat(mttLoyer).toFixed(2), 
      }); 
     }); 
} 

在希望這可以幫助別人後面!

+0

你知道這裏發生的事情嗎? – Hitmands

+0

隨着代碼在debbuging模式下運行,我清楚地看到順序是,所以如果我能幫忙,你有什麼不明白的地方? – rob1

+0

您應該更好地瞭解異步代碼的執行情況,而總和結果不會因它們的因素順序而改變,而是按照與輸入數據不同的順序執行操作... – Hitmands