asynchronous - Async false in ajax requests using jquery -


i have calendar control on site. fetches availability data server using ajax request. here code -

var monthlybookingdetails = getbooking(month, year);//getbooking ajax function //rest of code  

here in getbooking function if make async: false, works browser blocked till ajax request serviced.

so thought of turn around -

while(monthlybookingdetails.length <= 0){//busy waiting} 

but feel not proper way, want understand correct way busy waiting , block following lines execute.

there problem code, you're right:

while(monthlybookingdetails.length <= 0){//busy waiting} 

that says "do infinite loop until monthlybookingdetails less or equal 0". deliberately introducing infinite loops (even if eventually broken) not sensible move. since, if ajax fails, infinite loop won't broken.

the correct way embrace asynchronous way. means callbacks. means supplying function called when asynchronous code complete.

so inside getbooking this:

function getbooking(month, year, callback) {     $.ajax({         /* settings */         success: function() {             callback(); // call callback function         }     }); } 

you call function this:

getbooking(month, year, function() {     /* code here */ }); 

this pattern familiar if have used jquery much. present in kinds of asynchronous actions, e.g. ajax , animation.

you want pass data callback. in normal fashion: callback(data) , getbooking(month, year, function(data) {.


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -