Executing one function after another

zen picture zen · Sep 26, 2013 · Viewed 9.2k times · Source

All of these functions are in the main function which is called after jQuery async AJAX success event and it runs every second. Each of the three functions call specific functions within them as well.

This is the basic javascript code I have:

function mainFunction() {
    function selectView(){
       // do stuff
    }
    function startWidgets(){
       // do stuff
    }
    function popData(){
       // do stuff
    }
    $.when(selectView()).then(startWidgets).then(popData);
}

function ajaxCall(){
    ajaxRequest = $.ajax({
        type: "GET",
        url: "",
        data: {},
        async: true,
        cache: false,
        timeout:50000,

        success: function(data){
            mainFunction();
            setTimeout(
                ajaxCall, 5000
            );
        },
        error: function() {
            // error stuff
        },
        complete: function() {
            // complete stuff
        }
    });
}    

selectView() - Uses jQuery .load() method to load HTML structure based on specific AJAX data.

startWidgets() - Initializes widgets by placing them into the HTML structure (based on IDs and classes). Only runs the first time.

popData() - Populates data to all other widgets based on AJAX data.

I tried $.when(selectView()).then(startWidgets).then(popData);

But that did not work. My problem is startWidgets usually runs before selectView, but since there's no HTML markup yet, it fails. I need them to run in that specific order and one doesn't start till previous one is done.

Answer

Arun P Johny picture Arun P Johny · Sep 26, 2013

You need to return the promise objects from selectView, if you are not returning a promise from selectView then when will consider the object as resolved and execute the success handlers.

Also I think it is best to handle the callbacks using .done()

function mainFunction() {
    function selectView(){
       // do stuff
       var xhr = $.ajax(....);
       ....
       return xhr;
    }
    function startWidgets(){
       // do stuff
    }
    function popData(){
       // do stuff
    }
    $.when(selectView()).done(startWidgets).done(popData);
}