javascript - AngularJS:具有 promise 和非 promise 数据的功能

标签 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 是在 promise 被 resolved 之后加载的。我怎样才能等到 promise 解决后再返回值?我是否在此函数中创建另一个 promise ?

最佳答案

该函数本身必须返回总价的 promise ,该价格取决于所有 (all) 创建的 promise 的决议。

首先,一点因式分解将有助于解决这个问题:

// 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
});

关于javascript - AngularJS:具有 promise 和非 promise 数据的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38596876/

相关文章:

javascript - AngularJS + Ionic - 如何使用延迟 promise 从第一个 Controller 调用第二个 Controller 上的方法?

javascript - 如何在 Angular 输出中通过 "get"获得信息?

javascript - 格式化 ngb-timepicker,使其返回为字符串而不是对象

javascript - 获取元素并追加到新的 div

javascript - 仅从 firebase : Angularfire 检索父元素

angularjs - Angular - $scope 无法访问服务中的 $http 响应

javascript - Angular2 中 Angular 的 $q 等价于什么?

javascript - XMLHttpRequest 与 JS Window 对象有何关系

javascript - removeAttribute 删除 "disabled"但不删除 "checked"

angularjs - 路由更改时不会触发 routeChangeStart