0

I'm looking for a solution to ensure that the three functions that I created run in an ordered sequrence once the first has completed.

Currently I have something like this which does not seem to work at all.

$(document).ready(function() {
    $.when(runPending(selectedYear, name)).then(runApproved(selectedYear,name)).then(runRejected(selectedYear,name));

});


function runPending(year, name){
    var deferred = new jQuery.Deferred();
    $.getJSON(URL, function() {
    }).done(function(json) {
        if(json.length == 0){
            console.log("No Data came back!");
        }
        else{
            //do stuff set to html_output_pending;

            $('#display').append(html_output_pending);
            }//end else

    }).fail(function(xhr, status, error) {
        alert(xhr.responseText);
    });
    return deferred.promise();
}

function runApproved(year, name){
    var deferred = new jQuery.Deferred();
    $.getJSON(URL, function() {
    }).done(function(json) {
        if(json.length == 0){
            console.log("No Data came back!");
        }
        else{
            //do stuff set to html_output_pending;

            $('#display').append(html_output_pending);
            }//end else

    }).fail(function(xhr, status, error) {
        alert(xhr.responseText);
    });
    return deferred.promise();
}

function runRejected(year, name){
    var deferred = new jQuery.Deferred();
    $.getJSON(URL, function() {
    }).done(function(json) {
        if(json.length == 0){
            console.log("No Data came back!");
        }
        else{
            //do stuff set to html_output_pending;

            $('#display').append(html_output_pending);
            }//end else

    }).fail(function(xhr, status, error) {
        alert(xhr.responseText);
    });
    return deferred.promise();
}

How do I ensure that once runPending has been completed and appended its data to the div element #display, execute the second function in order to the third.

Any help on this would be greatly appreciated!

Thank you.

5
  • Javascript doesn't multitask. Unless you are doing asynchronious calls in your functions or they fire handlers with logic you rely on, then simply calling each function would work. Commented Jun 11, 2014 at 14:43
  • @Vld I do a $.getJSON on each function. Perhaps that's what causing it? Commented Jun 11, 2014 at 14:47
  • That is absolutely causing it. I'll update my answer. Commented Jun 11, 2014 at 14:47
  • Indeed - AJAX calls would be the thing. if you do not rely on them being asynchroinious, you could flip the async flag to false but it might be a better idea if you attach the functions you need to the success handlers of each. Commented Jun 11, 2014 at 14:49
  • 2
    Correction - getJSON does not have an async flag. You would need to add them to the success handler. Commented Jun 11, 2014 at 14:51

1 Answer 1

2

Javascript functions run sequentially, so:

$(function() {
   runPending(selectedYear, name);
   runApproved(selectedYear, name);
   runRejected(selectedYear, name);
}

Will work just fine. If your runPending, runApproved, and runRejected functions are more complicated such that they are calling asynchronous functionality, they should return promises (jQuery and $q implement them slightly differently). This is when your promise chaining (when, then, then...) would be appropriate.

In the case of $.getJson as you have updated with, you would do something like this:

$(function() {
   $.when(runPending(selectedYear, name))
   .then(runApproved(selectedYear, name))
   .then(runRejected(selectedYear, name));
}

function runPending(x,y){
    return $.getJson(someUrl).done(function(stuff) {
        $('#display').append(stuff);
    }
}

function runApproved(x,y){
    return $.getJson(someOtherUrl).done(function(stuff) {
        $('#display').append(stuff);
    }
}

function runRejected(x,y){
    return $.getJson(someThirdUrl).done(function(stuff) {
        $('#display').append(stuff);
    }
}

If what you are doing is very process-intensive such that the done handler may take longer than the following request/done handler, you could do something like this:

$(function() {
   $.when(runPending(selectedYear, name))
   .then(runApproved(selectedYear, name))
   .then(runRejected(selectedYear, name));
}

function runPending(x,y){
    var deferred = new $.Deferred();

    $.getJson(someUrl).done(function(stuff) {
        $('#display').append(stuff);
        deferred.resolve('success');
    }

    return deferred.promise();
}

function runApproved(x,y){
    var deferred = new $.Deferred();

    $.getJson(someOtherUrl).done(function(stuff) {
        $('#display').append(stuff);
        deferred.resolve('success');
    }

    return deferred.promise();
}

function runRejected(x,y){
    var deferred = new $.Deferred();

    $.getJson(someThirdUrl).done(function(stuff) {
        $('#display').append(stuff);
        deferred.resolve('success');
    }

    return deferred.promise();
}
Sign up to request clarification or add additional context in comments.

9 Comments

is that same as having them in onload? Because if so, doesn't seem to be the case as they load in different order on each load
@Jaime Torres: What do you mean by run sequentially? What if one of those functions involved a network operation or a setTimeout(), that could cause the next function to start before the result of the previous one has completed.
In the example provided, he didn't have any asynchronous functionally in his code,but has eluded to it in his newer comments.
@JaimeTorres can you explain the reason behind "return" on each json when it is already appending the result to the div on call?
Sure, the return is retuning the promise so we know when to fire the next item. The done is doing the work of the append once it's done. Techincally, if you had an insanely fast response, you might run into a race-case where the items didn't append in the correct order. If this is a concern (very small probability), you could create your own promise in the function, and then complete it in the done of each getJson.
|

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.