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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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