Offir Pe'er Offir Pe'er - 4 months ago 7
Ajax Question

Jquery invoke $.when after a function finished

I have the following code:

isPublisher.done(function(isActive) {
if (isActive) {
AddRoleToUser(inlineUid, "Publisher");
}
$.when(SetCountryAndLanguage(), GetUserRoles()).done(SetInlineManualTracking);
});

//Add Role to inline manual table in DB.
function AddRoleToUser(userId, role) {
return $.ajax({
type: "POST",
url: "../Publisher/Service.asmx/AddRoleToUser",
data: JSON.stringify({ id: userId, role: role }),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}


I want the
$.when
to occur only after
AddRoleToUser
function finished. How can I achieve that?

Answer

I want the $.when to occur only after AddRoleToUser function finished.

That's what your current code does. But assuming AddRoleToUser starts an asynchronous process, and you want to wait until that process completes, AddRoleToUser will need to accept a callback or return a promise.

If we assume it returns a promise, then you can have your call to $.when wait for that to resolve (using a dummy promise instead if you don't call it):

isPublisher.done(function(isActive) {
    var p;
    if (isActive) {
        p = AddRoleToUser(inlineUid, "Publisher");
    } else {
        p = $.Deferred().resolve().promise();
    }
    p.then(function() {
        $.when(SetCountryAndLanguage(), GetUserRoles()).done(SetInlineManualTracking);
    });
});