jquery done()下的代码在when()之前执行

时间:2012-11-16 20:40:09

标签: javascript jquery jquery-deferred

为什么done()语句下的代码在when()下调用的另一个3函数之前执行?它会立即发生。我以为什么时候用来排队功能和完成用来执行什么时候代码是什么时候完成...

$(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/

1 个答案:

答案 0 :(得分:5)

您需要使用$ .Deferred()并返回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/