is $ajax() call with a successcallback really asynchronous

I am kind of confused right now. I have the following asynchronous ajax call where I am passing a successcallback.

ajax('PUT', 'some URL', successCallback, data);

I observe that this callback is called when the request completes so I fail to understand how this call is asynchronous if it waits for the call to complete.

If I do not pass the successcallback to ajax and return the callback from the function I can observe asynchronous behavior as expected

ajax('PUT', 'some URL', undefined, data);
return successcallback();

With above change I actually observe the ajax call executing asynchronously and my page can proceed but if the page redirects to some other link the the request gets cancelled. So the only option that works is passing in succesCallback for ajax but it seems to be syncronous rather than asynchronous

Answers 1

  • I think you have your terminology backwards. "Asynchronous" in this context means "runs at some future point in time and doesn't block immediate execution of code". "Synchronous" is a blocking call, one that will halt execution until it's complete.

    The callback there is intended to be executed when the request is complete, which is by definition "asynchronous". Your alternate version runs the success callback regardless, and it does that long before the AJAX call is initiated as well as not knowing if it will succeed.

    You need to do asynchronous calls otherwise the JavaScript code and engine are completely jammed waiting for a response. This used to be acceptable when this is a separate process with no other responsibilities, but it's a disaster in a web application where your code likely has other things it has to respond to.

Related Articles