簡體   English   中英

使用Ember的承諾

[英]Using promises with Ember

我正努力在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()

});

任何意見,將不勝感激。

有兩個問題,首先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

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM