Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running functions serially and parallel

Tags:

jquery

ajax

I've 3 functions : func1, func2 and func3.

func1 and func2 use load() to fetch content dynamically.

func3 runs on content loaded by func2 and shows an animation on it.

I want func1 and func2 to run parallel (for better performance) and then I want func3 to run once the previous two are done.

    var funcList = ['func1','func2'];
    $.each(funcList, function(i,v){
            window[v]();
    })
    func3();

I notice that the animation of func3() doesn't run probably because the content of func2 wasnt fetched yet. I ran func3() from the console once the page was loaded and the animation ran fine. Why is this happening? Isn't each() synchronous ?

like image 627
soundswaste Avatar asked May 22 '26 10:05

soundswaste


1 Answers

that is because $.ajax is asynchronous.. by the time func3 is called , there is no guarantee that the other two ajax call have been completed successfully..you can use $.when to check the returned promise and once the two function is resolved run the third function.

try this

$.when(funcList).then(func3) 

example

var func1=function(){
  return $.get('url',function(data){....});
}

var func2=function(){
  return $.get('url2',function(data){....});
}

function func3(){
  // animation here
}

$.when(func1(),func2()).then(func3) 
like image 154
bipen Avatar answered May 24 '26 02:05

bipen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!