2016-07-26 104 views
1

我有一個函數,它具有承諾數據和簡單數學值的組合數據。這裏的功能:AngularJS:具有承諾數據和非承諾數據的函數

_getTotalPrice = function() { 

      var price = 0; 
      // Simple Math data. 
      // Calculate price for channels first. 
      price = price + (num_channels - 5)*(4); 


      var themepacks = cart.themepacks; 
      if(themepacks) { 
       angular.forEach(themepacks, function(pack, index) { 

       // data coming from a service 
       channelFactory.getThemePack(pack).then(function(result) { 
        price = price + Number(result.packPriceAmt); 
        console.log("price", price); 
        }); 
       }); 
      } 

      console.log(" Total price", price); 
      return price; 
}; 

在頁面加載的時間,Total priceprice是不同的價值。這是因爲承諾解決後,price被加載。在返回值之前如何等待承諾解決?我是否在這個功能中創造了另一個承諾?

+1

做了你看看$ Q?請參閱http://www.codeducky.org/q-serial/或其他示例。 – Naveen

+2

你不能*等待函數內返回一個值。它要麼返回'return'或'undefined'作爲隱式返回返回。返回一個返回值的承諾。 – estus

回答

1

該函數本身必須返回總價格的承諾,該總價格取決於創建的承諾分辨率的所有(all)。

首先,小保將幫助它清除掉:

// return a promise for a theme pack price 
function priceOfPack(pack) { 
    return channelFactory.getThemePack(pack).then(function(result) { 
     return Number(result.packPriceAmt); 
    }); 
} 

這使得更清楚的是,我們要收集一套的價格異步的想法。現在的循環是簡單...

_getTotalPrice = function() { 
    var themepacks = cart.themepacks || []; 
    var promises = []; 
    angular.forEach(themepacks, function(pack, index) { 
     promises.push(priceOfPack(pack)); 
    }); 
    var basePrice = (num_channels - 5) * 4; 

    // when all promises are resolved, they will be with an array of prices 
    return $q.all(promises).then(function(result) { 
     return result.reduce((a, b) => { a + b }, basePrice); 
    }); 
} 

調用者必須認識到,新的函數返回一個承諾,並相應地改變,所以......

_getTotalPrice().then(function(result) { 
    // result is the totalPrice 
}); 
+0

'if(!themepacks)'? – charlietfl

+0

@charlietfl,是的,我沒有提供整個_getTotalPrice方法。只是與承諾有關的部分。 – danh

+0

猜測OP不知道他們需要另一個承諾返回其他條件 – charlietfl

1

試試這個:

_getTotalPrice = function() { 

      var price = 0; 
      // Simple Math data. 
      // Calculate price for channels first. 
      price = price + (num_channels - 5)*(4); 


      var themepacks = cart.themepacks; 
      if(themepacks) { 
       angular.forEach(themepacks, function(pack, index) { 

       // data coming from a service 
       return channelFactory.getThemePack(pack).then(function(result) { 
        price = price + Number(result.packPriceAmt); 
        return $q.when(price); 
        }); 
       }); 
      } 
      else{ 
       return $q.when(price); 
      } 
}; 

_getTotalPrice().then(function(price){ 
    console.log(price); 
}); 

這將是異步功能。

+0

返回裏面forEach什麼也不做,你需要該循環創建的數組。解決方案將無法正常工作 – charlietfl

+0

哦,我錯過了他的forEach 所以代替ü需要使用: 回報$ q.all(承諾)。然後(函數(結果){ angular.forEach(結果,函數(結果){ price = price + Number(result.packPriceAmt); }); return $ q.when(price); }); – uamanager

+0

沒有意見張貼在評論...只是更新回答 – charlietfl