我可以保证在jQuery中返回已填充的对象吗? [英] Can I make a promise return a populated object in jQuery?
本文介绍了我可以保证在jQuery中返回已填充的对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对整套Deferred/Promise原则并不陌生,但是在阅读了全部内容之后,我所能找到的是关于如何使用它们返回ajax数据而不是javascript对象的信息.那可能吗?目的是使以下代码起作用:
I am new to the whole set of Deferred/Promise principles, but after reading about it all I can find is about how to use them to return ajax data, not a javascript object. Is that possible? The goal is to make the following code work:
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);
});
推荐答案
我认为类似的方法应该起作用:
I think something like this should work:
this.getData = function(){
var deferred = $.Deferred();
deferred.resolve(new Binary(this.data));
return deferred.promise();
};
您将返回一个promise
,而不是返回数据本身,在这种情况下,该promise
已经被解析,因此done
回调可以立即使用您解析它的数据进行调用.
Instead of returning the data itself, you return a promise
, which in this case has already been resolved, so the done
callback can get called immediately with the data you resolve it with.
这篇关于我可以保证在jQuery中返回已填充的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文