簡體   English   中英

Strongloop諾言內循環

[英]Strongloop promise inside loop

我試圖在for循環內調用回送查找功能,將迭代中的值傳遞給回送功能。 該代碼的主要問題可以通過以下方式表示:

for (var a = 0; a < $scope.countries.length; a++) {
  $scope.getEmFacPurElec($scope.countries[a], 'ton/kWh', 'CO2e').then(function(result) {
    emFacPurElecToUse = $scope.emFacPurElecs;
}

這是被調用的函數:

$scope.getEmFacPurElec = function (country, unit, ghgType) {
   var defer = $q.defer();
   $scope.emFacPurElecs = [];

   $scope.emFacPurElecs = Country.emFacPurElecs({
      id: country.id,
      filter: {
               where: {
                       and: [
                             {unit: unit},
                             {ghgType: ghgType}
                            ]
                      }
              }
   });   

   defer.resolve('Success getEmFacPurElec');
   return defer.promise;
};             

問題在於,將調用回送承諾函數,然后返回未定義的值,這意味着在獲取要分配給emFacPurElecToUse的值之前,它將移至for循環的下一個迭代。 在移至下一個國家之前,我需要針對該國家/地區對該變量進行更多計算。

我已經看過使用$ q.all作為可能的解決方案,並按照http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html(Rookie錯誤#2:WTF,如何將ProEach()與Promise一起使用?),但我只是想不出如何將它們組合在一起以使其工作。 我應該改用forEach嗎?

我還看到此鏈接的角度為$ q,如何在for循環內和之后 (以及其他類似的請求)鏈接多個promise,但我沒有需要在for循環內處理的多個promise。 我需要為該國家/地區檢索一個emFacPurElecs的價值,並對其進行一些處理,然后再移至下一個國家/地區。 我覺得自己很親密,但是我無法理解如何編寫此特定功能。 任何幫助是極大的贊賞。

在我看來,您確實在for循環中有多個承諾要處理,因為您說“在移至下一個國家之前,我需要對該國家/地區的變量進行更多計算”。 這一切都應該在我建議的承諾鏈calcEmFacPurElec

$scope.calcEmFacPurElec = function (country, unit, ghgType) {
   $scope.getEmFacPurElec(country, unit, ghgType).then(function(countryEmFacPurElecs) {
    // do something with countryEmFacPurElecs

    return countryEmFacPurElecs;
}

$scope.getEmFacPurElec = function (country, unit, ghgType) {
   var defer = $q.defer();

   defer.resolve(Country.emFacPurElecs({
      id: country.id,
      filter: {
               where: {
                       and: [
                             {unit: unit},
                             {ghgType: ghgType}
                            ]
                      }
              }
   });   );
   return defer.promise;
};      

希望以上內容是正確方向的指針!

當您要對一組項目執行承諾鏈時,那么正如您所確定的,Promise.all(使用您需要的任何承諾實現)就是您想要的。 .all接受一個Promises數組,因此在for循環中,您可以執行以下操作:

var promises = []; 
for (var a = 0; a < $scope.countries.length; a++) {
  promises.push($scope.calcEmFacPurElec($scope.countries[a], 'ton/kWh', 'CO2e')); // new promise chain that does all of the work for that country
}

$q.all(promises).then(function(arrayofCountryEmFacPurElecs) {console.log('all countries completed')});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM