Skip to content Skip to sidebar Skip to footer

Were Ember Computed Properties Meant To Be Used With / Contain Asynchronous Code?

I'm an experienced Ember.js developer. In guides, we can find an example of Computed Property with full name (synchronous, easy, relies on first name and last name). In the wild, w

Solution 1:

I assume you mean mixing computed properties and promises. If you do then don't. I have stumbled upon this issue multiple times. I find it problematic especially with deep nested associations.

I was working on an eCommerce site as well. Initially, I discovered a lot of calculations didn't get resolved when the site rendered. The reason was because I passed promises into computed property(which is used for calculation). Later on, I realized I should resolve all relationships before passing results into calculation logics instead. I did this step in a service. One example to demonstrate what I mean:

Let's say, order has many items and you want to calculate total price, price is a field in item.

Instead of:

total: Ember.computed("order.items.@.price", function() {
  return this.get("order.items").reduce((sum, obj) => {
    return sum + obj.get("price");
  });
});

I do this:

total: Ember.computed("items.@.price", function() {
   return this.get("items").reduce((sum, obj) => {
     return sum + obj.get("price");
   });
});

where items is passed in as a promise result somewhere above.

I found this post explains why-you-should-not quite well.

I tempted to ask similar question a while back. Keen to hear more ideas about this.


Post a Comment for "Were Ember Computed Properties Meant To Be Used With / Contain Asynchronous Code?"