【发布时间】:2017-10-27 09:53:08
【问题描述】:
这里我尝试顺序加载几个 JS 文件。问题是$.when 不等待链完成。但最后一个 $.Deferred.then 按预期工作。我应该怎么做才能使$.when 工作?
var urls = [
"https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js",
"https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.js",
"https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe-ui-default.js"
];
var xxx = $.Deferred();
xxx.then(function() {
options = {
dataType: "script",
url: urls[0],
cache: false
};
return $.ajax(options).promise();
})
.then(function() {
options = {
dataType: "script",
url: urls[1],
cache: false
};
return $.ajax(options).promise();
})
.then(function() {
options = {
dataType: "script",
url: urls[2],
cache: false
};
return $.ajax(options).promise();
}).then(function() {
$("body").append("This is correct. All files are loaded.<br>");
});
$.when(xxx).done(function() {
$("body").append("This is wrong. JS files are not loaded yet.<br>");
});
xxx.resolve();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
【问题讨论】:
-
如果它按预期使用
$.Deferred.then,那么为什么要使用$.when? -
完全没有理由在这里使用
$.when()或您的$.Deferred()。以$.ajax(...).then()开始链。您的最后一个.then()处理程序应该可以很好地知道整个链何时完成。当 return$.ajax(...)工作正常时,也没有理由使用return $.ajax().promise()。