0

I have functions that do AJAX requests, how can I make these functions execute in order they are called in JavaScript?

function1(); // some
function2(); // AJAX
function3(); // happens
function4(); // in
function5(); // each function

I want function2 to wait until function1 is complete and function3 to wait until function2 is complete and so on...

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
  • 8
    JavaScript already works that way. If your functions are starting asynchronous operations, you have to adapt your program to that fact. – Pointy Jul 29 '12 at 14:14
  • What behavior do you observe when you have your code written that way? – YePhIcK Jul 29 '12 at 14:15
  • 1
    @Pointy: They get executed in that order but I think the OP is looking for a way to queue them, see the second line. – Wesley Murch Jul 29 '12 at 14:16
  • @WesleyMurch well clearly there's something we're not being told, but it could be several things. Are they to be executed in the future? In response to user interaction? Are they firing off asynchronous HTTP requests? – Pointy Jul 29 '12 at 14:17
  • im getting results from function3 before function1 and function2 are executed – user1561051 Jul 29 '12 at 14:18
  • @user1561051 Can you post the content of the functions? – Loïc Faure-Lacroix Jul 29 '12 at 14:19
  • @user1561051: This is really context dependent, need to see your actual code, and you should provide an explanation of your use case (for one reason, to see if you actually need this). – Wesley Murch Jul 29 '12 at 14:19
  • that's not normal except you have Ajax in other functions – codingbiz Jul 29 '12 at 14:19
  • im calling these functions onpageload and yes function1 is firing a XMLHttpRequest – user1561051 Jul 29 '12 at 14:20
  • @user1561051 well then the "results" from the first function won't actually arrive at the browser until long, long after it has returned. – Pointy Jul 29 '12 at 14:26
  • Since you confirmed you have AJAX in them, I've edited this in your question. Otherwise it'd look like "how to make JS work exactly how it works already". – Oleg V. Volkov Jul 29 '12 at 15:19

1 Answers1

4

Javascript is Asynchronous so you need to have a callback on each function that does something when that function is finished.

More info : http://recurial.com/programming/understanding-callback-functions-in-javascript/

Here is some info on how to add callbacks to your functions :

adding callback to function - always

Community
  • 1
  • 1
LiamB
  • 18,243
  • 19
  • 75
  • 116