【发布时间】:2014-10-26 17:42:37
【问题描述】:
如标题所述,我的问题很奇怪。代码如下:
案例一:
var first = $.ajax({ // about 500ms request
url: myUrl
success: function() { console.log(1); }
});
var second = $.ajax({ // about 200 ms request
url: myUrl
success: function() { console.log(2); }
});
$.when(first, second).done(function() { console.log(3); });
记录 2、1、3。一切都很好,正是我想要的。
案例 2:
var first = $.ajax({ // about 500ms request
url: myUrl
success: function() { console.log(1); }
});
var second = $.ajax({ // about 200 ms request
url: myUrl
success: function() { console.log(2); }
});
function logthree() {
console.log(3);
}
$.when(first, second).done(logthree());
日志 3、2、1,这是一个问题。 logthree() 函数应该只在第一次和第二次解析时执行一次。
为什么会这样?我怎样才能在没有任何问题的情况下使用案例 2?
注意:如果 first 和 second 是函数并且它们返回 $.ajax,则会发生同样的情况。
注意:如果 first 和 second 都是 $.get,则会发生同样的事情。
【问题讨论】: