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

aar*_*ing 1 javascript jquery deferred-execution deferred

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

Str*_*ner 7

取自deferred.resolve()文档:

解析Deferred后,将调用deferred.then()或deferred.done()添加的任何doneCallback.回调按添加顺序执行.

示例如下:

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();
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="logEntry"></ul>
Run Code Online (Sandbox Code Playgroud)

  • 在你的例子中,`always`附加到`then`,这与OP要求的有点不同. (2认同)