Search code examples
jqueryajaxpromise.when

JQuery function returns promise but 'when' still doesn't wait


I've just learned about the $.when().then() functionality. I've been trying to make it work and I've looked at a lot of examples but I'm apparently not understanding fully yet because I can't make it work. I know that whatever function I pass as a parameter to the when() function must return a promise object. I feel like what I've done should work but it doesn't so clearly I'm still not understanding something. In my code below, loadUserInterfaceGroupsDropDown() is executing before the ajax call inside initializeUserInterfaceGroups() has completed. Notice that I return the results of the ajax call. That ought to yield the same as many of the simplistic examples that I saw that pass an ajax call as a parameter to the when() statement. Also I return a promise in the else statement at the bottom. But since this doesn't seem to be working I've obviously misunderstood something. Please help.

$.when(initializeUserInterfaceGroups()).then(loadUserInterfaceGroupsDropDown());

function initializeUserInterfaceGroups() {
    if (userInterfaceGroups === undefined) {
        // get the UserInterfaceGroups
        return $.ajax({
            type: "POST",
            url: "Users.aspx/GetUserInterfaceGroups",
            data: "{organizationId: " + $("#ddOrganization").val() + "}",
            datatype: "json",
            contentType: "application/json; charset=utf-8",
            success: function(response) {
                if (response.d.Success) {
                   userInterfaceGroups = response.d.UserInterfaceGroups;
                   //loadUserInterfaceGroupsDropDown();
                    renderCheckboxLists();
                } else {
                   alert(response.d.ErrorMessage);
                }
            },
            failure: function(response) {
               alert('Error getting the UserInterfaceGroups: ' + response.d);
            }
        });
    } else {
        return $.Deferred().promise();
    }
}

Solution

  • The proper syntax to use .when() and .then() promise with multiple ajax function is like below:

    $.when($.ajax(...), $.ajax(...)).then(function (resp1, resp2) {
        //this callback will be fired once all ajax calls have finished.
    });
    

    So basically you need to change your calling method like above. Hope it helps!