Photo by Matt Lee on Unsplash

How to handle async properties in Ember.js

Maciej Kwaśniak
Macsour
Published in
2 min readDec 12, 2018

--

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.

Hire me as your next frontend engineer!

Check out my projects, experience, and ask me a question on macsour.com

--

--