0

为什么done()语句下的代码在调用下的其他 3 个函数之前执行when()?它立即进行。我认为 when 用于对函数进行排队,而 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/

4

1 回答 1

5

您需要使用 $.Deferred() 并返回承诺。

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

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

}

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

于 2012-11-16T20:47:36.660 回答