什么在jQuery中首先出现.always()或.then()回调?

时间:2015-04-23 00:28:16

标签: javascript jquery deferred deferred-execution

如果你有一个既有.then又有.always回调的函数,哪一个会先被执行?

1 个答案:

答案 0 :(得分:7)

取自deferred.resolve()文档:

  

解决Deferred后,添加任何doneCallbacks   调用deferred.then()或deferred.done()。回调被执行   按照他们被添加的顺序。

以下示例:



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();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="logEntry"></ul>
&#13;
&#13;
&#13;