jaynp
jaynp

Reputation: 3325

Order of execution when using synchronous $.ajax call

I am trying to understand how synchronous ajax calls fit in with the order of execution, because I am getting some strange bugs.

// (1)
$.ajax({
  async: false,
  url: url0,
  dataType: 'json',
  success: function(data) { 
       // (2)
  });
// (3)

Is it true that with synchronous ajax calls, the order of evaluation will be (1), followed by (2), and then always followed by (3)? I want to particularly verify that (3) is only executed after the entire body of (2).

Upvotes: 0

Views: 219

Answers (1)

troelskn
troelskn

Reputation: 117427

Yes, but it's not the right way to go about this. Instead, move the code in (3) into the success handler (2).

Can you explain a little more why it matters if they achieve the same effect? What if (2) has nothing to do with the data gotten from the ajax call?

A synchronous call will block the browsers runtime until it completes. This means that the UI is completely unresponsive for the user.

If you want to logically separate your current (2) from (3), you can bind multiple success handlers like this:

var d = $.ajax({
  url: url0,
  dataType: 'json'
});
d.success(function() {
  // (2)
});
d.success(function() {
  // (3)
});

They will be executed in sequence.

Upvotes: 1

Related Questions