How to handle async properties in Ember.js
--
Many times I encounter a question about how to handle async properties in Ember. I saw a lot of solutions like overwriting property after promise will resolve or handling promise in a template using special helpers. But there is also another, much simpler way!
You can use PromiseProxyMixin + ObjectProxy (or ArrayProxy if needed).
Example usage:
Explanation:
Instead of resolving a promise inside of our property:
viewCount: computed('articleId', function() {
return this.fetchArticleStats(this.articleId).then((stats) => {
return stats.viewCount;
});
}).readOnly(),
We are creating ObjectPromiseProxy
using PromiseProxyMixin
inside of our async property.
articleStats: computed('articleId', function() {
let promise = this.fetchArticleStats(this.articleId);
return ObjectPromiseProxy.create({ promise });
}),
And then just referring our property to that object:
viewCount: reads('articleStats.viewCount').readOnly()
Hint:
The property will stay empty until the promise will not resolve
Thanks to this trick, you can “observe” whatever async property you wish in your component, handle loading state or display them whenever it will be possible.