2015-04-23 92 views
1

如果你有一個函數既有.then又有.always回調函數,哪一個函數會先執行?jQuery中的第一個.always()或.then()回調是什麼?

+3

你爲什麼不只是嘗試一下,看看,我猜',然後()' – adeneo

+0

而我只是做了,拿了1分鐘,而我是對的 - > ** http://jsfiddle.net/adeneo/ou1sy6uw/** – adeneo

+1

但是,交換它們,它們返回的方式不同 - > ** http://jsfiddle.net/adeneo/ou1sy6uw/1/ **,所以無論他們添加的順序 – adeneo

回答

5

deferred.resolve()文檔摘自:

當延遲得到解決,通過 deferred.then()或deferred.done()添加任何doneCallbacks被調用。回調按照添加順序執行 。

下例:

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>

+1

在您的示例中,「always」與「then」相關,這與OP要求的有所不同。 – zerkms

相關問題