Offir Pe'er Offir Pe'er - 4 months ago 9
jQuery Question

Execute a function in JQuery after 2 functions were finished

I have been struggling with this issue all day and couldn't figure out how to make a function that is relay on 2 functions results to execute right after they both finish.

I Tried doing this:

$.when(SetCountryAndLanguage(), GetUserRoles()).done(SetInlineManualTracking());


But is goes to
SetInlineManualTracking()
right away without waiting to the 2 functions to finish their jobs.
How can I execute the third function after both functions finish while keeping the async advantages?

This is function number 1:

//Gets the country the user is in and later set the player language.
function SetCountryAndLanguage() {
$.get("http://ipinfo.io", function() {}, "jsonp").
done(function(response) {
inlineCountry = response.country;
}).
done(SetInlineManualLanguage);
}


Function number 2:

//Gets the user roles from the db and update the tracking.
function GetUserRoles() {
debugger;
$.ajax({
type: "POST",
url: "../Publisher/Service.asmx/SelectUserRoles",
contentType: "application/json; charset=utf-8",
dataType: "json"
}).
done(UpdateRoles);
}


And the third function that depends on the other 2 previous functions:

function SetInlineManualTracking() {
debugger;
//<!-- User tracking data -->
window.inlineManualTracking = {
uid: inlineUid, // Only this field is mandatory
email: Cookies.get('email'),
username: inlineUserName,
name: Cookies.get('name'),
created: new Date().getTime() / 1000,
updated: new Date().getTime() / 1000,
group: inlineCountry,
roles: userRoles
}
}

Answer

You need to make the functions you execute return the promises from $.get and $.ajax respectively. Then you need to provide the reference of SetInlineManualTracking to done() instead of executing it immediately. Try this.

$.when(SetCountryAndLanguage(), GetUserRoles()).done(SetInlineManualTracking);

function SetCountryAndLanguage() {
    return $.get("http://ipinfo.io", function() {}, "jsonp").done(function(response) {
        inlineCountry = response.country;
    }).done(SetInlineManualLanguage);
}

function GetUserRoles() {
    return $.ajax({
        type: "POST",
        url: "../Publisher/Service.asmx/SelectUserRoles",
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(UpdateRoles);
}

Note that as SetInlineManualLanguage, UpdateRoles and SetInlineManualTracking are in done handlers of the requests, they may execute at the same time. This should not be an issue, unless one of them is dependant on the result of the other.

Comments