What comes first .always() or .then() callbacks in jQuery? [duplicate]

爱⌒轻易说出口 提交于 2019-12-11 13:36:09

问题


If you have a function which has both .then and .always callbacks, which one will get executed first?


回答1:


Taken from the deferred.resolve() documentation:

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.

Example below:

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>


来源:https://stackoverflow.com/questions/29811418/what-comes-first-always-or-then-callbacks-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!