7

我正在努力在 Ember 控制器中链接承诺。

为了说明我在JSBIN上做了一个例子

此处还包括 Ember 代码:

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()

});

任何意见,将不胜感激。

4

1 回答 1

12

有两个问题,第一个this在promise回调中不可用,因为它是异步的,这意味着promise被解决的时间this不再是指控制器,所以你需要预先将值存储在某个地方,正如你所看到的我们将它存储在一个名为self. 其次.property(),您的第二个功能也应该被删除,因为据我所知,它不需要。此外,您应该使用.send([methodname])而不是直接调用控制器方法或使用点符号

这给我们留下了这些修改,使您的示例工作:

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"));
  }

});

上面的代码产生了这个控制台输出:

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

在这里你的工作jsbin

希望能帮助到你。

于 2013-09-24T14:37:54.083 回答