使用Ember的承诺

时间:2013-09-24 14:21:10

标签: javascript ember.js promise

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

为了说明我在JSBIN here

上做了一个问题的例子

此处还包括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()

});

任何建议都将受到赞赏。

1 个答案:

答案 0 :(得分:12)

有两个问题,第一个this在promise回调中不可用,因为它是异步的,这意味着解析了promise的时间this不再引用控制器,所以你需要存储这个值预先在某处,你可以看到我们将它存储在名为self的var中。第二,你的第二个函数的.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

希望它有所帮助。