Search code examples
jqueryjquery-deferreddeferred.when

How to have first function "foo1()" finished processing before running $.when() afterward??


I'm using JQuery v2.0.0

How do I make these functions run in top to bottom order instead of an asynchrous-like effect or order, meaning don't let the function "foo2()" run before the function "foo1()" is done first.

foo1();

$.when( foo2() )
    .done(function() { $('#test').dialog('close');  foo3(); })
    .fail(function() { alert('You have a problem!!');  foo3(); });

Thanks...


Solution

  • Assuming foo1 looks something like this:

    function foo1() {
        var promise = $.Deferred();
        $.ajax({...}).done(function() { promise.resolve(); })
            .fail(function() { promise.reject(); });
        return promise;
    }
    

    You can do this:

    foo1().done(function() {
        $.when( foo2() )
            .done(function() { $('#test').dialog('close');  foo3(); })
            .fail(function() { alert('You have a problem!!');  foo3(); });
    });
    

    ...or as @Kevin B mentioned, like this:

    foo1().done(function() {
        foo2()
            .done(function() { $('#test').dialog('close');  foo3(); })
            .fail(function() { alert('You have a problem!!');  foo3(); });
    });
    

    ...but as comments point out, a better implementation of foo1 would look like this, which you can do as long as foo1 doesn't need to do any custom work during done, fail, or always.

    function foo1() {
        return $.ajax({...});
    }
    

    Otherwise, if foo1 is not async in any way, it will always complete first.