-1

I have several Javascript functions and one button to trigger them all together. Some of the functions depend on the content generated by a previous function. The issue I have is that some functions are not triggered or run correctly because the previous one isn't completed yet (most of them are ajax calls). So how do I make sure that a function is triggered when the previous one is completed?

The topics I found here were to complex for me to understand or just didn't provide me an answer.

function CallAllFunctions(){
    function1();
    function2();
    function3();
}

Thank you very much in advance!

SidOfc
  • 4,552
  • 3
  • 27
  • 50
Dr.Mojo
  • 27
  • 12
  • 1
    You need to do `function CallAllFunctions(){function1(function(){function2(function3)})}` – slebetman Feb 18 '16 at 09:23
  • Can you please be more precise? your case seems to be slightly complex to be summarized in a generic example, mostly because of your sentence: _(most of them are ajax calls)_ . Are them ALL ajax calls or just some of them? if so, you may want to call the next function in the ajax callback or, if you just need to perform N ajax requests in a specific order, you may just want to queue the ajax calls correctly. – briosheje Feb 18 '16 at 09:35

3 Answers3

0

Try this

Solution 1

function function1(){
   // some code

}

function function2(){
   // some code
}

$.ajax({
   url:function1(),
   success:function(){
   function2();
}
})

Second Solution

$.when( function1() ).done(function() {
       function2();
});

Have a look at this

Community
  • 1
  • 1
Rahul
  • 763
  • 1
  • 12
  • 45
0

You can call a call back function after a function,

function myDinner( param1, param2, callbackFunction ) { 
  alert( 'Started eating my dinner. \n\n It has: ' + param1 + ', ' + param2); 
  callbackFunction ();
 }
myDinner ( 'Rice', 'Curry', function() { alert( 'Finished eating my dinner.' ); });

This link will be helpful.

Sravan
  • 18,467
  • 3
  • 30
  • 54
0

If each function is an individual AJAX request you could setup a request chain and wait until each function was executed successfully.

CG_FD
  • 597
  • 1
  • 4
  • 15