jQuery $.ajax Async vs Synchronous Revisit

A conversation came up about how some folks like to turn $.ajax into synchronous by specifying “async: false”. 

jQuery documentation states “Setting this option to false (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.”

The motivation of make the $.ajax() synchronous is usually due to the caller function needing to do something with the $.ajax result.  Here is the concept code:

   1: function doSomething() {

   2:     var result = getAPIValue();

   3:     console.log("Do something with " + result);

   4: }

   5:  

   6: function getAPIValue() {

   7:     var result;

   8:     $.ajax({

   9:         type: "GET",

  10:         async: false,

  11:         url: "http://api.xxxx.com/",

  12:         dataType: "json',

  13:         success: function(data) {

  14:             result = data.word;

  15:         },

  16:         error: function(e) {

  17:             console.log(e.message);

  18:         }

  19:     });

  20:     return result;

  21: }

 

The recommended way is use callback.  Here is an example:

   1: function doSomething() {

   2:     getAPIValue(processResult);

   3: }

   4:  

   5: function processResult(result)

   6: {

   7:     console.log("Do something with " + result);

   8: }

   9:  

  10: function getAPIValue(callback) {

  11:     $.ajax({

  12:         type: "GET",

  13:         url: "http://api.xxxx.com/",

  14:         dataType: "json',

  15:         success: function(data) {

  16:             callback(data.word);

  17:         },

  18:         error: function(e) {

  19:             console.log(e.message);

  20:         }

  21:     });

  22: }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s