2

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();
    }
}
Mahesh Singh Chouhan
  • 2,558
  • 1
  • 16
  • 26
Dar
  • 383
  • 1
  • 5
  • 16
  • `$.Deferred().promise();` returns a promise that is never resolved. I don't think that is what you want. – Bergi May 17 '17 at 18:45

3 Answers3

2

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!

Mahesh Singh Chouhan
  • 2,558
  • 1
  • 16
  • 26
0

this doesn't seem to be working - I've obviously misunderstood something.

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

Yes, two things:

  • You absolutely don't need $.when when you already have a promise. You should only use it when you're not sure whether the return value of the call is a promise, or when you have multiple promises to await. Neither is the case here.
  • then takes a callback function. You must not call loadUserInterfaceGroupsDropDown() right away (which is why it doesn't wait) and pass the results to then, you must pass the function itself. (Or at least wrap the call in a function expression).

So your code should read

initializeUserInterfaceGroups().then(loadUserInterfaceGroupsDropDown);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

I thought I'd update what I've done. I was still learning new things about how to best use this. In the end it was still the perfect answer to what I needed but I did have to change some things around. Somebody pointed out that I am returning an unresolved promise in my else statement in one of my ajax calls. While that seems to be working for me the time being, that is something I'll need to research some more. Here is my working code in the hopes it will help someone. I do this because even after getting the right answer there were still things I had to figure out so hopefully this will help somebody:

$.when(getUserInterfaceGroups(), getUserDetail($(this).attr("data-userId"))).done(function(resp1, resp2) {
    renderUserInterfaceGroupControls(resp1[0], resp2[0]);
    populateForm(resp2[0]);
});

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

function getUserDetail(userId) {
    return $.ajax({
        type: "POST",
        url: "Users.aspx/GetUser",
        data: "{userId: " + userId + "}",
        datatype: "json",
        contentType: "application/json; charset=utf-8",
        failure: function (response) {
            alert('Error getting the User details: ' + response.d);
        }
    });
}

function renderUserInterfaceGroupControls(resp1, resp2) {
    if (resp1.d.Success && resp2.d.Success) {
        userInterfaceGroups = resp1.d.UserInterfaceGroups;
        loadUserInterfaceGroupsDropDown(resp2.d.UserDetail.InterfaceModeId);
        renderCheckboxLists();
    } else {
        alert(response.d.ErrorMessage);
    }
}

function populateForm(response) {
    if (response.d.Success) {
        var userDetails = response.d.UserDetail;
        $("#txtUserCode").val(userDetails.UserCode);
        $("#txtName").val(userDetails.Name);
        $("#txtPassCode").val(userDetails.PassCode);
        $("#ddUserInterfaceGroup option[value='" + userDetails.UserInterfaceGroupId + "']").prop("selected", true);
        $("#txtEmail").val(userDetails.Email);
        $("#dtBirthDate").val(userDetails.DateOfBirth);
        $.each(userDetails.ContactGroupIds, function (idx) {
            $("div input[type=checkbox][value=" + userDetails.ContactGroupIds[idx] + "]").prop('checked', true);
        });
        if (userDetails.AssetTagNumber === "") {
            $("#rbUserOwned").prop("checked", "checked");
        } else {
            $("#txtAssetTag").val(userDetails.AssetTagNumber);
        }
        $("#hidUserId").val(userDetails.Id);
        showInputFields();
    } else {
        alert(response.d.ErrorMessage);
    }
}
Dar
  • 383
  • 1
  • 5
  • 16