为什么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";
}
答案 0 :(得分:5)
您需要使用$ .Deferred()并返回promise。
function func1(first) {
var dfd = $.Deferred();
var t = setTimeout(function() {
$('body').append(first);
dfd.resolve();
}, 800);
return dfd.promise();
}