[英]Is this the correct use of $.Deferred in this situation?
I have the following code withhn a module 我有以下代码与模块
var def = $.Deferred();
$.getJSON("http://localhost:62588/api/Values/getXMLData")
.done(function(json){
def.resolve($.parseJSON(json));
});
return def;
I then have to call it from another module so it completes, before calling a processing the returned data. 然后,我必须从另一个模块中调用它,以使其完成,然后再调用处理返回的数据。
repository.getUserPolicies().done(function (userPolicies) {
process(userPolicies);
});
This works well but I don't yet quite understand how the deferred object works yet. 这很好用,但我还不太了解延迟对象的工作原理。
I have read that you can use getJSON's deferred object but not sure if that's exactly what I'm doing here? 我读过您可以使用getJSON的延迟对象,但是不确定这是否正是我在这里所做的?
I was wondering if there are any disadvantages of this approach? 我想知道这种方法是否有缺点?
Can it be done more elegantly? 可以更优雅地完成吗?
Thanks 谢谢
No, this is not a good use of $.Deferred
, as $.getJSON
already has a deferred object built in with the added support of promises etc. in newer versions of jQuery. 不,这不是
$.Deferred
,因为$.getJSON
已经内置了一个延迟对象,并在较新版本的jQuery中增加了对promises的支持。
You can use that built in deferred object, and just return the ajax call, and attach the done()
function to that directly: 您可以使用该内置的延迟对象,只需返回ajax调用,然后将
done()
函数直接附加到该对象即可:
var repository = {
getUserPolicies: function() {
return $.getJSON("http://localhost:62588/api/Values/getXMLData");
}
}
repository.getUserPolicies().done(process);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.