d4rty d4rty - 1 year ago 65
Javascript Question

Using local JS functions together with jQuery instruction $.when()

I want to execute several ajax requests and wait until all are done and then continue using the jQuery


For php scripts this works fine, I have created several functions like this:

function ajax1() {
var settings = {
type: "GET",
url: "root/scripts/script.php",
return $.ajax(settings);

But how would this work if I additionally want to wait for JS functions, which is located at a different location thann the

For example a
function abc()
, located in
. How can I perform an AJAX call on a function located in a local JS file and add this to the
construct? Such that:

$.when(ajax1(), ajax2()).done(function(a1, a2){
//a1[0] is the return value from the php script
//a2[0] is the return value from the function abc()

Answer Source

Since JS is executed sequentially, it should be enough to include the abc() function as the first line of the $.when body.

This executes abc() only after all the ajax calls are done:

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
    $.getScript( "file_where_abc_is.js", function( data, textStatus, jqxhr ) {

The lines below abc() will not be executed until all the ajax calls are done and the abc() function is completed.

The previous approach would make it easy to avoid calling abc() if one of the ajax returns a specific value/error. Also you can make sure all the ajax calls are done before calling abc(). Or call different functions depending on the result of the ajax calls. I'm not sure if you require any of these.

If you don't mind or care when abc() is called you can also do it the other way around:

$.getScript( "file_where_abc_is.js", function( data, textStatus, jqxhr ) {
    $.when(ajax1(), ajax2(), ajax3(), ajax4(), abc()).done(function(a1, a2, a3, a4, abcAnswer) {

Yet another version, similar to the last one:

function ajaxABC() {
    $.getScript( "file_where_abc_is.js", function() {
         return abc();

$.when(ajax1(), ajax2(), ajax3(), ajax4(), ajaxABC()).done(function(a1, a2, a3, a4, abcAnswer) {
     // ....

PS: Have not executed the code, there may be some minor parts to fine tune.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download