I am working with Ember Data and trying to create a computed property equal to the sum all products in a store with their respective discounts applied. I am new to promise chaining and I believe that this is an issue with how I am formatting the chain.
export default DS.Model.extend({
title: DS.attr('string'),
storeProducts: DS.hasMany('storeProduct',{async:true}),
totalStoreValue:function(){
store.get('storeProducts').then(function(storeProducts){ //async call 1
return storeProducts.reduce(function(previousValue, storeProduct){ //begin sum
return storeProduct.get('product').then(function(product){ //async call 2
let price = product.get('price');
let discount = storeProduct.get('discount');
return previousValue + (price * discount);
});
},0);
}).then(function(result){ //
return result;
});
}.property('storeProducts.@each.product'),
Any help and suggestions would be appreciated.
Use Ember.RSVP.all
to resolve your list of promises before calculating the total:
store.get('storeProducts').then((storeProducts) => { //async call 1
return Ember.RSVP.all(storeProducts.map(storeProduct => {
return storeProduct.get('product').then((product) => { //async call 2
let price = product.get('price');
let discount = storeProduct.get('discount');
return price * discount;
});
}));
}).then(function(result){ //
return result.reduce((prev, curr) => {
return prev+curr;
}, 0);
});