javascriptjqueryajaxdeferred

jQuery when function does not evaluate the deferred object


I'm having an issue with jQuery deferred object. I'm creating a promise inside a function that will do a ajax call and saving a data to server. I know jQuery ajax having a predefine deferred object.

var AddCodes = function(XML ){
    var def = $.Deferred();

    $.ajax({
        type: "POST",
        url: "webservicename.asmx/SaveCode",
        data: "{" + XML + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function () {
            def.resolve();
        },
        error: function (jqXHR, status, error) {
            def.reject();
        }
    });

   return def.promise();
}

then I'm evaluating the function like this:

$.when(AddCodes(XML)).then(function(){
    processData();
}

If the AddCodes() function is executed successfully only I'm calling another function to insert some data into database, because both are dependent function.

The problem is when function doesn't evaluate deferred object. processData() never worked. I'm using deferred first time to my project. Please help me to sort this issue.


Solution

  • The documentation says that $.when() accepts both deferred objects (created with $.Deferred() and plain objects, which are considered as already fulfilled promises.

    If a single argument is passed to jQuery.when and it is not a Deferred, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.

    But AddCodes() doesn't return anything. If you return your deferred object (def) this should work.

    So, if you change your code to

    var AddCodes = function(XML ){
        var def = $.Deferred();
    
        $.ajax({
            ....
        });
    
        return def.promise();
    }
    

    you should be ok. Note that this is just like the first example here.