Photo by Matt Lee on Unsplash

How to handle async properties in Ember.js

Maciej Kwaśniak
Dec 12, 2018 · 2 min read

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:

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

Macsour

The Macsour blog

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store