If you have a function which has both .then
and .always
callbacks, which one will get executed first?
Asked
Active
Viewed 1.1k times
3

aaron-coding
- 2,571
- 1
- 23
- 31
-
4Why don't you just try it and see, I'm guessing `then()` – adeneo Apr 23 '15 at 00:29
-
1And I just did, took one minute, and I was right -> **http://jsfiddle.net/adeneo/ou1sy6uw/** – adeneo Apr 23 '15 at 00:31
-
2However, swapping them, they return differently -> **http://jsfiddle.net/adeneo/ou1sy6uw/1/**, so whatever order they are added – adeneo Apr 23 '15 at 00:33
-
The best would be to not rely on the order. Single threaded JS by default is protected from concurrency issues, if only we don't do silly things in our code. – zerkms Apr 23 '15 at 01:16
-
OP, please rephrase your title to be more specific... – einpoklum Apr 23 '15 at 05:43
1 Answers
9
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>
-
2In your example `always` is attached to `then`, which is a bit different from what OP asked. – zerkms Apr 23 '15 at 01:19