我是整套延遲/承諾原則的新手,但在閱讀後我能找到的所有內容都是關於如何使用它們返回ajax數據,而不是JavaScript對象。那可能嗎?我們的目標是使下面的代碼工作:我可以做一個承諾返回jQuery中的填充對象嗎?
var Binary = function(data){
this.data = data;
}
var File = function(url){
this.data = null;
this.url = url;
this.getData = function(){
// return either cached version at this.data or fetch it
}
}
// the goal is to make the following possible:
var url = "http://www.google.com/humans.txt";
var file = new File(url);
file.getData().done(function(binary){ //binary should be equals to `new Binary(data)`
alert("we got binary data object with the data being: " + binary.data);
});
如果你的操作有時異步有時同步的,那麼你就可以回到一個早已解決的承諾的同步路徑,然後主叫可以把結果看作是異步的,或者不是。如果結果總是同步產生,那麼沒有理由使用承諾。 – jfriend00 2014-12-07 19:31:47
哪個諾言味道,你想在答案? ['jQuery.deferred'](http://api.jquery.com/jQuery.Deferred/)? [ES6承諾](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)?承諾/ A +? – 2014-12-07 19:32:17
@FabrícioMattéjQuery.deferred – chacham15 2014-12-07 19:32:39