soundswaste
soundswaste

Reputation: 3074

Running functions serially and parallel

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 ?

Upvotes: 3

Views: 2966

Answers (1)

bipen
bipen

Reputation: 36531

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) 

Upvotes: 2

Related Questions