Friday, December 28, 2018

javascript - How to make code wait while calling asynchronous calls like Ajax




I am looking for something like this




function someFunc() {

callAjaxfunc(); //may have multiple ajax calls in this function
someWait(); // some code which waits until async calls complete
console.log('Pass2');

}

function callAjaxfunc() {

//All ajax calls called here
console.log('Pass1');

}


What I have tried?



1
Jquery.when()




tried using it..it works fine. But not the way I want. $.when will wait but the code next to $.when() runs with out waiting. The code inside do callback only runs after ajax calls



2.
setTimeOut() with a global flag



I was so confident this will work. I tried like following.



GlobalFlag = false;


function someFunc()
callAjaxfunc(); //may have multiple ajax calls in this function
setTimeOut(waitFunc, 100); // some which waits until async calls complete
console.log('Pass2');
}

function callAjaxfunc() {
//All ajax calls called here
onAjaxSuccess: function() {
GlobalFlag = true;

};
console.log('Pass1');
}

function waitFunc() {
if (!GlobalFlag) {
setTimeOut(waitFunc, 100);
}
}​



Still not able to get wanted result. Am I doing something wrong here? This is not the way?



Result I wanted should come like this



Pass1
Pass2


Not able to make any fiddle as it needs AJAX calls




EDIT: As many were suggesting callbacks..i know about them..but still the code next to somewait() will get executed...I want browser to completely stop executing code next to somewait() until the ajax call..Also it may be a bad practice but worth to know and try if possible...


Answer



Use callbacks. Something like this should work based on your sample code.



function someFunc() {

callAjaxfunc(function() {
console.log('Pass2');
});


}

function callAjaxfunc(callback) {
//All ajax calls called here
onAjaxSuccess: function() {
callback();
};
console.log('Pass1');
}



This will print Pass1 immediately (assuming ajax request takes atleast a few microseconds), then print Pass2 when the onAjaxSuccess is executed.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...