wheresrhys wheresrhys - 2 months ago 10
jQuery Question

Are jquery deferred callbacks synchronous if the deferred is already resolved?

I'm guessing the answer's yes but the code's not the easiest to decipher. And in the docs it says


Any callbacks added to the object with deferred.then(), deferred.always(), deferred.done(), or deferred.fail() are queued to be executed later. Calling deferred.resolve() or deferred.resolveWith() transitions the Deferred into the resolved state and immediately executes any doneCallbacks that are set.


But this doesn't explicitly cover the case of attaching a callback to an already resolved Deferred.

Answer

If the promise is already resolved / rejected, the new callbacks are executed synchronously.

From the jQuery.deferred() doc:

Once the object has entered the resolved or rejected state, it stays in that state. Callbacks can still be added to the resolved or rejected Deferred — they will execute immediately.

Demo (Fiddle):

var def = jQuery.Deferred(),
    promise = def.promise();
console.log('before 1');
promise.done(function () {
    console.log('done 1');
});
console.log('after 1');
def.resolve();
console.log('before 2');
promise.done(function () {
    console.log('done 2');
});
console.log('after 2');

Output:

before 1
after 1
done 1
before 2
done 2
after 2