0

In short the question is:

jQuery.ajax({
    url: some_url,
    success: function(){
        alert('success1');
    },
    error: function(){
        alert('error1');
    }
});
jQuery.ajax({
    url: some_url,
    success: function(){
        alert('success2');
    },
    error: function(){
        alert('error2');
    }
});
jQuery.ajax({
    url: some_url,
    success: function(){
        alert('success3');
    },
    error: function(){
        alert('error3');
    }
});

Will these always result in:

alert('success1');
alert('success2');
alert('success3');

Or can the output be like:

alert('success2');
alert('success3');
alert('success1');

Shouldn't I run abort() on previous AJAX requests if I want the last one's output to be displayed to the user only? I mean I don't mind them seeing success1 and success2 messages as long as success3 will be always the last one.

Jimsea
  • 585
  • 1
  • 6
  • 11
  • give a short explanation about your query. – Sudhanshu Saxena Jul 24 '14 at 12:47
  • 4
    They will execute in the order they are encountered, but because ajax is asynchronous, there's no guarantee that they will finish in any given order. – adeneo Jul 24 '14 at 12:48
  • They tend to go in the same order but it can fail, specially if the request are of different sizes. For example if you send part of a file every part is 8192b every time, but the last part maybe just 1b so it will happen that the last part will go first than the previous part. – peterpeterson Jul 24 '14 at 12:49
  • You can't control or predict how the server will behave. – Pointy Jul 24 '14 at 12:49
  • so the the solution would be to create a queue class that will order them and fill process the next one just when the previous one is finished. – peterpeterson Jul 24 '14 at 12:50
  • You can't guarantee, possible solution here: [Queue Ajax Requests][1] [1]: http://stackoverflow.com/questions/4785724/queue-ajax-requests-using-jquery-queue – peterpeterson Jul 24 '14 at 12:52
  • Isn't there a option into the JQuery.ajax() function that can make them synchronous? Or if they are always in the same order you could call each one in the success function of the previous one? – Sebastien Jul 24 '14 at 13:18

1 Answers1

0

Try to read about JavaScript Promises/A+ (i.e. here http://www.html5rocks.com/en/tutorials/es6/promises/) This could be helpful. It allows to do smth. like doSmthAsync().then(doSmthAsyncElse()).then(...) and so on

Also, jQuery deffered could help you. http://api.jquery.com/jquery.deferred/

Dmitry Volokh
  • 1,630
  • 16
  • 28