If I have a function that sometimes returns a deferred object but sometimes a non-deferred object. How can I tell which one it is?
The Deferred object, introduced in jQuery 1.5, is a chainable utility object created by calling the jQuery. Deferred() method. It can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
A deferred object is an object that can create a promise and change its state to resolved or rejected . Deferreds are typically used if you write your own function and want to provide a promise to the calling code. You are the producer of the value. A promise is, as the name says, a promise about future value.
A promise represents a value that is not yet known. This can better be understood as a proxy for a value not necessarily known when the promise is created. A deferred represents work that is not yet finished. A deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.
Depending on your use case, you could also use jQuery.when
[1]:
If a single argument is passed to
jQuery.when
and it is not a Deferred, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.
With jQuery.when
you can treat your mysterious object always as deferred:
// x could be a deferred object or an immediate result var x = getMysteriousObject(); // success will be called when x is a deferred object and has been resolved // or when x is an immediate result jQuery.when( x ).then( success, error );
[1] http://api.jquery.com/jQuery.when/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With