Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using promises with Ember

I'm struggling to chain promises in an Ember controller.

To illustrate I've made an example of the issue on JSBIN here

Also included the Ember code here:

App.IndexController = Ember.Controller.extend({
  result_of_request: 'nothing',

  first_request: function() {

    // create a promise which is immediately resolved
    var promise = new Ember.RSVP.Promise(function(resolve, reject){
      resolve("first resolved");
    });

    // once the promise has resolved it should call the next function?
    promise.then(function(data) {
      // does log the data (has resolved)...
      console.log("data is : " + data);

      // but neither this
      this.set("result_of_request", "first");

      // nor this work
      second_request();
    }); 
  }.property(),

   second_request: function() {
    console.log("second request");
  }.property()

});

Any advice would be appreciated.

like image 216
Chris Avatar asked Sep 24 '13 14:09

Chris


1 Answers

There are two problems, first this is not available inside the promise callback because it's async, this means the time the promise is resolved this no more refers to the controller, so you need to store the value beforehand somewhere, as you can see we store it in a var called self. And second the .property() on your second function should also be removed because it's not needed as far I can see. Furthermore you should use .send([methodname]) instead of invoking the controller methods directly or using the dot notation.

This leaves us with this modifications making your example work:

App.IndexController = Ember.Controller.extend({
  result_of_request: 'nothing',

  first_request: function() {
    var self = this;

    // create a promise which is immediately resolved
    var promise = new Ember.RSVP.Promise(function(resolve, reject){
      resolve("first resolved");
    });

    // once the promise has resolved it should call the next function?
    promise.then(function(data) {
      // does log the data (has resolved)...
      console.log("data is : " + data);

      self.set("result_of_request", "first");

      self.send("second_request");
    }); 
  }.property(),

   second_request: function() {
    console.log("second request");
    console.log(this.get("result_of_request"));
  }

});

The above code yields this console output:

"data is : first resolved"
"second request"
"first"

And here your working jsbin.

Hope it helps.

like image 97
intuitivepixel Avatar answered Oct 02 '22 12:10

intuitivepixel