我有一个函数,其数据是 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 price
和price
的值是不同的。这是因为 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/