305

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 ?

Sujith PS
  • 4,776
  • 3
  • 34
  • 61
Joe D
  • 3,588
  • 2
  • 19
  • 14
  • Yeah, seems to me it should be called something other than "Ajax" (Asynchronous JavaScript And XML) if it's not asynchronous... – devlord Aug 31 '12 at 01:07
  • looks similar to this question: [http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req](http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req) makes the call synchronous.... – CSharpAtl Sep 25 '09 at 16:34
  • Asynchronous means that the script will send a request to the server, and continue it's execution without waiting for the reply. As soon as reply is received a browser event is fired, which in turn allows the script to execute associated actions. – SagarPPanchal Feb 24 '14 at 06:43

7 Answers7

335

Does it have something to do with preventing other events on the page from firing?

Yes.

Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.

For more insight see: jQuery ajax success anonymous function scope

Community
  • 1
  • 1
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • 15
    I've always wondered how this was accomplished, since JavaScript is not threaded. – Matt Sep 25 '09 at 16:46
  • 1
    So it's like a cheap way to do deferred execution? – Lorenzo Sep 11 '12 at 00:16
  • 5
    @L.DeLeo - no, not at all - deferreds are another way of managing the complexity of asynchronous function calls - `async: false` *removes the asynchronousity from the call completely*. The call to `ajax` **blocks** - the code that follows it is not executed until the server has responded. – Sean Vieira Sep 11 '12 at 01:56
  • 17
    Remember that this also means that browser will not capture/trigger any events happening while ajax is being executed. I found this out the hard way, trying to figure out why Firefox was not triggering a click event. It turned out to be because of a "forced" blur event with a following sync call blocking it. – PålOliver Feb 19 '13 at 10:34
  • 4
    @Matt no it is not (anymore ^^) http://www.w3schools.com/html/html5_webworkers.asp – borrel Jul 11 '13 at 23:03
  • 11
    It seems `async: false` is dead, I tried it and got `18:17:49.384 Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/ 1 jquery.js:9061:4` – Aba Jan 31 '17 at 23:19
  • @downvoter - let me know what I can do to make the answer better! – Sean Vieira Mar 31 '17 at 21:54
  • @Matt It is just call back. I think it is not multithreaded. When request is finished (or at different state changes), the browser will call the specified call back functions. It is there in XMLHttpRequest also.. (As far as I understand) – Mohammed Shareef C Aug 04 '17 at 04:46
  • 3
    `async: false` is never required, it's crappy code - if you think you need it then you need to rethink what you're doing. You're given the methods to achieve what you hope to achieve with `async` set to `false` - that nothing can happen until the request is completed.... like `success` and `error`. Don't freeze peoples browsers it's so yuck. Hence the "bad user experience" deprecation warning. – zanderwar Oct 02 '20 at 06:10
  • @zanderwar: the user won't notice that delay thanks to the ajax call, but the async false can help to ensure that no unexpected things happen since the user's previous request is not yet finished. For example: i have a dropdown and the whole form must be reloaded via ajax after selection changed(alternatively redirect to another page). After it completed successfully i need to re-initalize all javascript events. Would this not be a valid use-case for async=false? – Tim Schmelter Feb 17 '21 at 12:41
  • 1
    @TimSchmelter No that would not be...there is no valid use case for async=false, your scenario is easily possible by continuing with execution in `success`.... it's deprecated, for very good reasons, it won't be supported in future thus anyone who uses it will need to update it when their clients start saying everything is broken. You can do it [properly](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) and you cannot call it AJAX if it's just JAX, aside... no one should condone the continued use of something that's deprecated... – zanderwar Feb 18 '21 at 02:26
  • @zanderwar: sometimes you need to block execution - while determining client authorisation, for example. You could run async false, or equivalent, or you could add all the extra code to set up a promise, or equivalent, and wait for it. Sometimes (all the time, actually) life isn't black-and-white. – EML Jan 25 '23 at 12:54
  • 1
    @EML If you need `async: false` you took the wrong direction way before winding up here. You have no choice when they remove support for it _from all browsers_ anyway. – zanderwar Jan 27 '23 at 00:19
  • @zanderwar: that's why I said "or equivalent". However, there are cases where it's pointless to add the extra code to handle promises - in a non-document environment, for example, where blocking isn't an issue. You should know by now that using phrases such as "no valid use case" is always going to be wrong. – EML Jan 27 '23 at 10:13
  • I know by now that there is no valid use case for `async: false`. Do better – zanderwar Jan 28 '23 at 07:12
143
  • 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.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
夏期劇場
  • 17,821
  • 44
  • 135
  • 217
30

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

Katia
  • 679
  • 2
  • 15
  • 42
Mohit
  • 331
  • 3
  • 6
20

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

Harsh Gupta
  • 444
  • 3
  • 9
  • Just in case anyone else has the same problem as me: This answer highlights that the `return php_data` statement cannot be in the success function, but has to be outside the `$.ajax()` function . I had put my equivalent of the `return php_data` inside the `success: function(){}` and it was always returning undefined – gordon613 Jul 04 '19 at 15:43
  • you can drop the `success` callback and shorten the code to something like: `var data = $.ajax({url: 'http://httpbin.org/get', async: false}).responseText;` – ccpizza Nov 28 '20 at 23:55
19

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.

John Millikin
  • 197,344
  • 39
  • 212
  • 226
11

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() {}
        });
    });
Hariprasad
  • 3,556
  • 2
  • 24
  • 40
Tony
  • 137
  • 1
  • 2
  • 59
    No amount of JavaScript will stop a browser window from closing – jammykam Jan 12 '14 at 16:16
  • I needed async false for something completely unrelated but it solved my problem since it allowed my script to grab a value from an xml file before populating it on the page as undefined. – J_L Oct 11 '19 at 21:58
9

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.

i474232898
  • 781
  • 14
  • 25