[jquery] What does "async: false" do in jQuery.ajax()?

Specifically, how does it differ from the default ( async: true ) ?

In what circumstances would I want to explicit set async to false, and does it have something to do with preventing other events on the page from firing ?

This question is related to jquery

The answer is


  • async:false = Code paused. (Other code waiting for this to finish.)
  • async:true = Code continued. (Nothing gets paused. Other code is not waiting.)

As simple as this.


One use case is to make an ajax call before the user closes the window or leaves the page. This would be like deleting some temporary records in the database before the user can navigate to another site or closes the browser.

 $(window).unload(
        function(){
            $.ajax({
            url: 'your url',
            global: false,
            type: 'POST',
            data: {},
            async: false, //blocks window close
            success: function() {}
        });
    });

Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.


From

https://xhr.spec.whatwg.org/#synchronous-flag

Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user's experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when the JavaScript global environment is a document environment. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an InvalidAccessError exception when it occurs. The future direction is to only allow XMLHttpRequests in worker threads. The message is intended to be a warning to that effect.


Setting async to false means the instructions following the ajax request will have to wait for the request to complete. Below is one case where one have to set async to false, for the code to work properly.

var phpData = (function get_php_data() {
  var php_data;
  $.ajax({
    url: "http://somesite/v1/api/get_php_data",
    async: false, 
    //very important: else php_data will be returned even before we get Json from the url
    dataType: 'json',
    success: function (json) {
      php_data = json;
    }
  });
  return php_data;
})();

Above example clearly explains the usage of async:false

By setting it to false, we have made sure that once the data is retreived from the url ,only after that return php_data; is called


If you disable asynchronous retrieval, your script will block until the request has been fulfilled. It's useful for performing some sequence of requests in a known order, though I find async callbacks to be cleaner.