jQuery 中的 .always() 或 .then() 回调先发生什么?
What comes first .always() or .then() callbacks in jQuery?
如果您有一个同时具有 .then
和 .always
回调的函数,哪个会先执行?
摘自 deferred.resolve()
文档:
When the Deferred is resolved, any doneCallbacks added by
deferred.then() or deferred.done() are called. Callbacks are executed
in the order they were added.
示例如下:
var $logger = $("#logEntry");
function addLog(content){
$logger.append($("<li/>").html(content));
}
var newPromise = $.Deferred();
$.when(newPromise).done(function() {
addLog("1st $when().done!");
});
newPromise.then(function() {
addLog("1st then!");
}).always(function() {
addLog("1st always!");
}).done(function() {
addLog("1st done!");
}).done(function() {
addLog("2nd done!");
}).always(function() {
addLog("2nd always!");
}).then(function() {
addLog("2nd then!");
});
$.when(newPromise).done(function() {
addLog("2nd $when().done!");
});
addLog("Resolving promise!");
newPromise.resolve();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="logEntry"></ul>
如果您有一个同时具有 .then
和 .always
回调的函数,哪个会先执行?
摘自 deferred.resolve()
文档:
When the Deferred is resolved, any doneCallbacks added by deferred.then() or deferred.done() are called. Callbacks are executed in the order they were added.
示例如下:
var $logger = $("#logEntry");
function addLog(content){
$logger.append($("<li/>").html(content));
}
var newPromise = $.Deferred();
$.when(newPromise).done(function() {
addLog("1st $when().done!");
});
newPromise.then(function() {
addLog("1st then!");
}).always(function() {
addLog("1st always!");
}).done(function() {
addLog("1st done!");
}).done(function() {
addLog("2nd done!");
}).always(function() {
addLog("2nd always!");
}).then(function() {
addLog("2nd then!");
});
$.when(newPromise).done(function() {
addLog("2nd $when().done!");
});
addLog("Resolving promise!");
newPromise.resolve();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="logEntry"></ul>