I’m an Ember guy and I use the promise implementation provided by Ember, which is compliant with the ES6 definition. Recently, I forgot about one feature of promises, and in the ensuing difficulties - I learned something new, which I’d like to share with you.
Ember meets API
Let’s say that you want to fetch some data from your API using Ember data in your model hook:
But you expect it to be risky. Your backend guys are having some troubles and sometimes the server doesn’t respond at that endpoint. Until they fix it, the error from this model hook is crashing your app into the error route. You want to make sure this doesn’t happen.
Bingo! When the server is down, the user is redirected to another route. However, you just broke the app... When the server is up, your
setupController action is getting an
undefined model. Why?
Deal with tricks in promises
Ok, I knew that promises are chainable, so I used the above approach. However, I forgot that
then are also chainable and that they return a new instance of the promise class, which will resolve to the value you return from
catch. What we did was transitioning but not returning anything, so the
model hook is basically returning
Are we stuck? No, there’s an easy and simple fix for this kind of situation:
As you see, we return the initial promise object from
store and chain on that promise in a completely different line of code. We don’t use the value returned from the chained method, and now everything works!
I hope you found this case interesting. Have you encountered any other interesting promise situations during your work in Emberjs? Let me know in the comments!
If Ember is one of your fields of interests, I have some interesting reads for you: