简体   繁体   中英

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?

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.

You can use that built in deferred object, and just return the ajax call, and attach the done() function to that directly:

var repository = {
    getUserPolicies: function() {
        return $.getJSON("http://localhost:62588/api/Values/getXMLData");
    }
}

repository.getUserPolicies().done(process);

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM