One of the niceties of Route
objects in Ember is that they accept and handle promises. However, I was wondering what the advantage is of returning a promise in a route's model
hook as opposed to an empty record or array of records that you populate when the corresponding API request(s) returns. It seems as if the result is similar, but I assume that I am overlooking something, that is, the advantage.
Since I'm a big fan of DRY I'm going to rather cite/extract the important paragraphs of the full article from the Router facelift done by Alex Matchneer to the ember Router
not long ago then explaining it with my own words.
Why?
- Semantic differences between app-initiated transitions and URL-initiated transitions made it very challenging in certain cases to handle errors or async logic
- Authentication-based apps were especially difficult to implement
redirect
was sometimes called when a promise model was resolved, sometimes not, depending on in-app/URL transitionSolution
The solution was to embrace async and make router transitions first class citizens. In the new API you are provided with the necessary hooks to prevent/decorate transition attempts via a
Transition
object passed to various hooks. These hooks are:
willTransition
events fired on current routes whenever a transition is about to take place.beforeModel/model/afterModel
hooks during the async validation phase.
...
model
and friendsIn this router iteration, transitionTo and URL changes behave the same way, in that any models provided via transitionTo or any models returned from the model hook will pause the transition if the model has a .then property (which indicates that it's a promise).
Since this addition to the ember Router
(release RC6) you will find code like the below in the source which IMHO looks beautiful and is very easy to understand:
From the source:
return RSVP.resolve().then(handleAbort)
.then(beforeModel)
.then(handleAbort)
.then(model)
.then(handleAbort)
.then(afterModel)
.then(handleAbort)
.then(proceed)
.then(null, handleError);
Here's the link to the full article again.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With