2013-09-24 52 views
6

我正在努力鏈接Ember控制器中的承諾。在Ember中使用承諾

爲了說明我做了問題的例子在JSBIN 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() 

}); 

任何意見,將不勝感激。

+0

'this'不是控制器內部的回調,'second_request'是方法(屬性)而不是函數(變量)。 – Bergi

回答

11

有兩個問題,第一this不可承諾回調,因爲它是異步裏面,這意味着承諾解決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

希望它有幫助。

+0

謝謝,這是一個非常明確的答案和解釋。最後,self.send在嘗試鏈接幾個promise時並不適用於我,並且最終使用帶有計算屬性的self.get來返回promise。只是覺得我會提到這一點對於任何嘗試同樣的事情的人。 – Chris