AngularJS:具有承诺和非承诺数据的函数

时间:2016-07-26 18:00:08

标签: javascript angularjs angular-promise

我有一个函数,其数据是promise数据和简单数学值的组合。这是功能:

_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。在返回值之前,我怎么能等到承诺得到解决?我是否在此功能中创建了另一个承诺?

2 个答案:

答案 0 :(得分: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);
 });

这将是异步功能。

答案 1 :(得分: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);
    });
}

调用者必须意识到新函数返回一个promise并相应地改变,所以......

_getTotalPrice().then(function(result) {
    // result is the totalPrice
});
相关问题