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

1

5

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

Janik answered 23/4, 2015 at 0:28 Comment(5)
Why don't you just try it and see, I'm guessing then()Devonadevondra
And I just did, took one minute, and I was right -> jsfiddle.net/adeneo/ou1sy6uwDevonadevondra
However, swapping them, they return differently -> jsfiddle.net/adeneo/ou1sy6uw/1, so whatever order they are addedDevonadevondra
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.Adelia
OP, please rephrase your title to be more specific...Herculean
N
10

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>
Nga answered 23/4, 2015 at 0:32 Comment(1)
In your example always is attached to then, which is a bit different from what OP asked.Adelia

© 2022 - 2024 — McMap. All rights reserved.