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...

11
  • 8
    JavaScript already works that way. If your functions are starting asynchronous operations, you have to adapt your program to that fact. Commented Jul 29, 2012 at 14:14
  • What behavior do you observe when you have your code written that way? Commented Jul 29, 2012 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. Commented Jul 29, 2012 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? Commented Jul 29, 2012 at 14:17
  • im getting results from function3 before function1 and function2 are executed Commented Jul 29, 2012 at 14:18

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

For the ones who don't understand async vs sync, see the explanation at this answer: stackoverflow.com/a/11689804.
Since when "Javascript is Asynchronous"?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.