0

Two AJAX requests exactly the same in every way apart from the order in which they are sent.

The only difference is the functions are executed at different times. function 1, then function 2.

Example pseudo code.

function 1 {
   $.getJSON(url , function(json_categories) { print json_categories + '1' });
}

function 2 {
   $.getJSON(url , function(json_categories) { print json_categories + '2' });
}

My question is can function 2 print before function 1?

1
  • that is asynchronous that is the reason you can not predict,use $.ajax and make that call synchronous by doing this sync :true
    – Sankara
    Jul 24, 2013 at 15:04

3 Answers 3

5

Yes, either response can arrive at any time. There are many variables involved, including network latency and server load. Additionally, there is nothing on the JavaScript side to enforce a particular order, they're both asynchronous callbacks wired to run whenever a response arrives.

2

If you need to wait for both requests to return use jQuery's $when() method:

$.when($.getJSON(url1), $.getJSON(url2)).then(function (json_categories1, json_categories2) { ... })
1

Yes, because it's an asynchronous call. You call URL and wait for the response, it's depends of many variables you cannot control. Set the async param "false" if you want to do a regular call (caution, it's deprecated and will be removed in future jQuery versions).

2
  • What is deprecated is the use of async:false together with promises, not the option itself. The problem with a synchronous request is that it will block the execution of any further js until the response arrives (making it impossible to give visual feedback in the ui, for example).
    – bfavaretto
    Jul 24, 2013 at 15:09
  • I totally agree with your opinion, it was for information if Aaron needed it.
    – Pouki
    Jul 24, 2013 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.