Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of returning a promise to a route's model hook?

Tags:

ember.js

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.

like image 979
Bart Jacobs Avatar asked Aug 12 '13 12:08

Bart Jacobs


1 Answers

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.

Embrace async...

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 transition

Solution

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 friends

In 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.

like image 105
intuitivepixel Avatar answered Nov 15 '22 18:11

intuitivepixel