Using promises with Ember

I am trying to bind promises in an Ember controller.

To illustrate, I gave an example of a JSBIN problem here

Ember code is also included:

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.

+6
source share
1 answer

There are two problems: the first this not available inside the promise callback, because it is asynchronous, which means the decision time for this promise no longer applies to the controller, so you need to store the value in advance, as you can see, we store it in var called self . And the second .property() for your second function should also be removed, because it is not needed, as far as I can see. In addition, you should use .send([methodname]) instead of calling controller methods directly or using dot notation.

This leaves us with these changes for your example to 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 gives this console output:

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

And here is your working jsbin .

Hope this helps.

+11
source

Source: https://habr.com/ru/post/954512/


All Articles