EmberJS - Router Pauses for Promises



The transition can be paused by returning a promise from the model hook. The transition can be completed immediately by returning normal objects or arrays from the model.

Syntax

Ember.Route.extend ({
   model() {
      return new Ember.RSVP.Promise(function(param) {
         //code here
      });
   }
});

Example

The example given below shows how transition will pause if the model returns a promise. Create a new route and name it as promisepause and open the router.js file to define the URL mappings −

import Ember from 'ember';                   
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config 

//The const declares read only variable
const Router = Ember.Router.extend ({
   location: config.locationType,
   rootURL: config.rootURL
});

//Defines URL mappings that takes parameter as an object to create the routes
Router.map(function() {
   this.route('promisepause');
});

//It specifies Router variable available to other parts of the app
export default Router;

Open the file application.hbs file created under app/templates/ with the following code −

<h2>Router Pauses for Promises</h2>
{{#link-to 'promisepause'}}Click Here{{/link-to}}

When you click the above link, it will open the promise pause template page. The promisepause.hbs file contains the following code −

{{model.msg}}
{{outlet}}

Now open the promisepause.js file created under app/routes/ with the following code −

import Ember from 'ember';
import RSVP from 'rsvp';

export default Ember.Route.extend ({
   model() {
      //RSVP.js is an implementation of Promises
      return new Ember.RSVP.Promise(function (resolve) {
         
         Ember.run.later(function () {
            //display the promise message
            resolve ({
               msg: "This is Promise Message..."
            });
         }, 3000); //time in milli second to display promise
      });
   }
});

Output

Run the ember server and you will receive the following output −

Ember.js Pause Promise

When you click on the link, model returns the promise which is not resolved until 3 seconds and when the promise fulfills, the router will start transitioning −

Ember.js Pause Promise
emberjs_router.htm
Advertisements