我可以在jQuery中返回一个填充对象的承诺吗?

我是整套Deferred / Promise原则的新手,但在阅读完所有内容后,我发现它是关于如何使用它们来返回ajax数据,而不是javascript对象。 那可能吗? 目标是使以下代码工作:

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); }); 

我认为这样的事情应该有效:

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

您不返回数据本身,而是返回一个promise ,在这种情况下已经解决了,因此可以使用您解决的数据立即调用done回调。

jquery ajax调用返回一个promise。 如果要缓存它,只需将文件实例“管道”到返回中

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