Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Deferred Not reaching last .then

I have a sequence of functions that must be executed. They all execute sequentially except the last one. d1 executes, d2 executes, d3 executes then the code inside the done function executes before the resolve of d4. Can't figure out why. Any help would be appreciated.

$(document).ready(function() {
    var d1 = functiond1();
    var d2 = functiond2();
    var d3 = functiond3();
    var d4 = functiond4();

    d1.then(d2).then(d3).then(d4).done(function() {

    //Code here does not wait for d4 to end before executing
    //HELP! 

    });
});

function functiond1() {
    var dfd = $.Deferred();

    //Do stuff here
    //Works in sequence

    dfd.resolve();
    return dfd.promise();
}


function functiond2() {

    var dfd = $.Deferred();
    params = jQuery.param({
        'parm1': 1,
        'parm2': 2,
        'parm3': 3
    });


    jQuery.getJSON($.webMethoJSONGet1, params).done(function(data) {

        //Do stuff here
        //Works in sequence

        dfd.resolve();

    });

    return dfd.promise();
}

function functiond3() {
    var dfd = $.Deferred();

    //Do stuff here
    //Works in sequence

    dfd.resolve();
    return dfd.promise();
}

function functiond4() {

    var dfd = $.Deferred();

    params = jQuery.param({
        'parm1': 1,
        'parm2': 2,
        'parm3': 3
    });

    jQuery.getJSON($.webMethoJSONGet2, params).done(function(data) {

        //Do stuff here
        //does not work in sequence

        dfd.resolve();

    });

    return dfd.promise();
}
like image 619
ricardo josé kercadó Avatar asked Oct 03 '15 16:10

ricardo josé kercadó


1 Answers

It's hard to tell what you are trying to do with those promises. You first call all 4 functions, and then you try to chain them with a bunch of then callbacks. If you want to sequentially chain them together it should look like this:

functiond1()
.then(functiond2)
.then(functiond3)
.then(functiond4)
.done(function() { /* blah */ });

If you just want a result after all have completed you can use $.when

$.when(functiond1(), functiond2(), functiond3(), functiond4())
.then(function(resultd1, resultd2, resultd3, resultd4) { /* blah */ });

On another note, in your functions you create promises that are resolved inside the done callback of another promise which is unnecessary. The $.getJSON.done() calls return a promise themselves so an additional promise is not needed. Just return the promise returned from done().

Sorry, I haven't messed much with jQuery deferred objects, but they appear similiar enough to standard Promises.

like image 158
Jason Rice Avatar answered Nov 18 '22 22:11

Jason Rice