Search code examples
javascriptember.jsember-model

How to wait until find method has finished before doing further processing in Ember Model


How can I wait until my find method has finished loading the model from the backend? After the model has loaded I want to fetch additional data and decorate my movie model with that data. The request to the external api from which the additional data is fetched is based upon properties of the movie model like year and title.

App.Movie.adapter = Ember.Adapter.create({
  find: function(record, objectId) {
    return Ember.$.ajax({
      headers: {
        'X-Parse-Application-Id': '',
        'X-Parse-REST-API-Key': ''
      },
      type: 'GET',
      url: 'https://api.parse.com/1/classes/Movie' + '/' + objectId
    }).then(function(data) {
      record.load(objectId, data);
    });
  }
});

App.MoviesMovieRoute = Ember.Route.extend({
  model: function (movie) {
    return App.Movie.find(movie.movie_id);
  },

  afterModel: function(movie, transition) {
    // currently undefined, undefined
    console.log(movie.get('title'), movie.get('year'));
  }
});

App.MoviesMovieController = Ember.ObjectController.extend({
  contentObserver: function () {
    // fetch additional data from external api
  }.observes('content')
});

Thank you


Solution

  • For ember model, use fetch, it will return the promise, and ember will wait until resolving that model before doing the next model.

    return App.Movie.fetch(movie.movie_id);
    

    find builds up a dummy record and returns the record immediately (and populates it when the data is available), whereas fetch builds up the record, and a promise, and returns the promise, which resolves to the record when it's been populated.

    They will both use the find method from the adapter.

    App.MoviesMovieRoute = Ember.Route.extend({
      model: function (movie) {
        return App.Movie.find(movie.movie_id);
      },
    
      afterModel: function(movie, transition) {
        // currently undefined, undefined
        console.log(movie.get('title'), movie.get('year'));
      },
    
      serialize: function(model){
        return { movie_id: model.get('whateverfieldhastheid')};
      }
    });