1252748
1252748

Reputation: 15372

code under jquery done() executes before when()

Why does the code under the done() statement execute before the other 3 function which are called under when()? It goes immediately. I thought when was used to queue up functions and done was used to execute something when the when code was, well, done...

$(document).on('click', '.ajax', function() {
    $.when(func1('<p>first</p>'), func2('<p>second</p>'), func3('<p>third</p>')).done(function() {
        $('body').append('all done');
    });
});

function func1(first) {

    var t = setTimeout(function() {
        $('body').append(first);
    }, 800);
    return "success";

}

function func2(second) {

    var t = setTimeout(function() {
        $('body').append(second);
    }, 2700);
    return "success";
}

function func3(third) {

    var t = setTimeout(function() {
        $('body').append(third);
    }, 200);
    return "success";
}​

http://jsfiddle.net/loren_hibbard/NhAFN/

Upvotes: 0

Views: 1153

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You need to use $.Deferred() and return promise.

function func1(first) {
    var dfd = $.Deferred();

    var t = setTimeout(function() {
        $('body').append(first);
        dfd.resolve();
    }, 800);
    return dfd.promise();

}

http://jsfiddle.net/NhAFN/2/

Upvotes: 5

Related Questions