Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if a jQuery object is deferred?

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?

like image 312
WawaBrother Avatar asked Jun 09 '12 22:06

WawaBrother


People also ask

What is deferred object in jQuery?

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.

What is jQuery deferred and promise object?

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.

What is the difference between a deferred and a promise?

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.


1 Answers

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/

like image 101
Julian Maicher Avatar answered Sep 18 '22 07:09

Julian Maicher