Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function after completion of all requests

I have two AJAX requests one after another-

var firstResult;
var secondResult;

FirstAjaxrequest({
        callback: function (options, success, response) {
            if(success)
            {
                firstResult = true;
            }
            else
            {
                firstResult = false;
            }
        }    
    });

SecondAjaxrequest({
     callback: function (options, success, response) {
            if(success)
            {
                secondResult= true;
            }
            else
            {
                secondResult= false;
            }
     }    
});

DisplayMessage(); // This function should display a message depending on     
                     FirstResult and secondResult
like image 932
Microsoft DN Avatar asked Jan 21 '13 14:01

Microsoft DN


2 Answers

You could create a variable for each request, signifying a successful request. Change this variable for each request respectively, when a successful request is made, then call your function.

Within your function simply check both variables, if they're both true, then both requests were successful, otherwise at least one was not and the if() condition will be false.

var firstResult = false,
    secondResult = false;

FirstAjaxrequest({
    callback: function (options, success, response) {
        if(success) {
            firstResult = true;
            DisplayMessage();
        }
    }    
});

SecondAjaxrequest({
    callback: function (options, success, response) {
        if(success) {
            secondResult= true;
            DisplayMessage();
        }
    }    
});

function DisplayMessage(){
    if(firstResult && secondResult){
        //Both requests successful
    } else {
        //Either still waiting for a request to complete
        // or a request was not successful.
    }
}
like image 127
George Avatar answered Nov 13 '22 01:11

George


There might be a better way to do it in EXTJS, but a plain JS solution is

var firstResult;
var secondResult;
var reqCount = 2;
var returnedCount = 0;

function isDone () {
    returnedCount++
    if ( returnedCount === reqCount ) {
         console.log(firstResult, secondResult);
    }
}

FirstAjaxrequest({
        callback: function (options, success, response) {
            if(success)
            {
                firstResult = true;
            }
            else
            {
                firstResult = false;
            }
            isDone();
        }    
    });

SecondAjaxrequest({
     callback: function (options, success, response) {
            if(success)
            {
                secondResult= true;
            }
            else
            {
                secondResult= false;
            }
            isDone();
     }    
});
like image 33
epascarello Avatar answered Nov 13 '22 02:11

epascarello