1

I have a calendar control on my site. It fetches some availability data from the server using some ajax request. Here is the code -

var monthlyBookingDetails = getBooking(month, year);//getBooking is ajax function
//rest of code 

Here in the getBooking function if i make async: false, it works but browser is blocked till the ajax request is serviced.

So I thought of a turn around as -

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

But I feel this is not the proper way, so just want to understand what is the correct way to do busy waiting and block the following lines to execute.

1 Answer 1

1

There is a problem with this code, you're right:

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

That says "do an infinite loop until monthlyBookingDetails is less than or equal to 0". Deliberately introducing infinite loops (even if they will eventually be broken) is not likely to be a sensible move. Especially since, if your AJAX fails, the infinite loop won't be broken.

The correct way to do this is to embrace the asynchronous way. That means callbacks. That means supplying a function that is called when your asynchronous code is complete.

So inside getBooking you would do this:

function getBooking(month, year, callback) {
    $.ajax({
        /* all your settings */
        success: function() {
            callback(); // call the callback function
        }
    });
}

You would then call the function like this:

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

This pattern will probably be familiar to you if you have used jQuery much. It is present in all kinds of asynchronous actions, e.g. AJAX and animation.

You will almost certainly want to pass data to your callback. You do this in the normal fashion: callback(data) and getBooking(month, year, function(data) {.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!!, I would place a callback in the complete : function(){} to avoid infinite loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.