Phillip Senn
Phillip Senn

Reputation: 47595

How to use jQuery's promises so that functions are not nested

I think I've added a layer of complexity. Here's what I've got:

;(function($, window, undefined) {
    function download() {
        var local = {};
        local.data = {};
        local.data.method = 'getMyData';
        local.dataType = 'json';
        local.Promise = $.ajax('myComponent.cfc', local);
        local.Promise.done(PromiseDone);
        local.Promise.fail(PromiseFail);
    }

    function PromiseDone(result) {};
    function PromiseFail(myEvent) {};
})(jQuery, window);

What I'd like to do is something like this:

;(function($, window, undefined) {
    var Variables = {};
    Variables.Promise = $.Deferred();

    function download() {
        var local = {};
        local.data = {};
        local.data.method = 'getMyData';
        local.dataType = 'json';
        Variables.Promise = $.ajax('myComponent.cfc', local);
    }

    Variables.Promise.done(function(result) {
    });
    Variables.Promise.fail(function(myEvent) {
    });
})(jQuery, window);

My goal is to flatten the JavaScript so that my functions aren't nested.

Q: Will my idea work, or does a deferred require a resolve in order to be considered done?

Upvotes: 0

Views: 187

Answers (1)

adeneo
adeneo

Reputation: 318182

You really have added unneccesary complexity. $.ajax already returns a promise, so there's no reason to create another one :

;(function($, window, undefined) {
    function download() {
        return $.ajax({
           data    : {method:'getMyData'},
           dataType: 'json'
        });
     }

    var ajaxCall = download();

    ajaxCall.done(function(result) {
          // do something with result
    });

    ajaxCall.fail(function() {
         // failed
    });
})(jQuery, window);

Upvotes: 2

Related Questions