2014-12-07 28 views
0

我是整套延遲/承諾原則的新手,但在閱讀後我能找到的所有內容都是關於如何使用它們返回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); 
}); 
+0

如果你的操作有時異步有時同步的,那麼你就可以回到一個早已解決的承諾的同步路徑,然後主叫可以把結果看作是異步的,或者不是。如果結果總是同步產生,那麼沒有理由使用承諾。 – jfriend00 2014-12-07 19:31:47

+1

哪個諾言味道,你想在答案? ['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

+0

@FabrícioMattéjQuery.deferred – chacham15 2014-12-07 19:32:39

回答

1

我覺得這樣的事情應該工作:

this.getData = function(){ 
    var deferred = $.Deferred(); 
    deferred.resolve(new Binary(this.data)); 
    return deferred.promise(); 
}; 

,而不是返回數據本身,就返回一個promise,在這種情況下早已已經解決,所以done回調可以立即與你解決它的數據調用。

+0

我認爲這是我正在尋找的,謝謝! – chacham15 2014-12-07 19:34:56

1

jquery ajax調用返回一個承諾。 如果你想你的文件實例緩存起來,只是「管」到返回

this.getData = function(){ 
    if (!this.dataPromise){ 
     this.dataPromise = $.ajax(url).then(function(data){ 
      return new File(data); 
     }); 
    } 
    return this.dataPromise; 
}; 
相關問題