How to determine if jQuery object is deferred?

If I have a function that sometimes returns a pending object, but sometimes not a pending object. How can I determine which one is there?

+44
javascript jquery jquery-deferred
Jun 09 2018-12-12T00:
source share
3 answers

Depending on your use case, you can also use jQuery.when [1]:

If one argument is passed to jQuery.when and it is not deferred, it will be considered as resolved by Deferred, and any completed copies attached to it will be executed immediately.

With jQuery.when you can always treat your mysterious object as lazy:

 // 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/

+48
Aug 28 2018-12-12T00:
source share

Since jQuery Deferreds are created by copying methods of a hidden object instead of calling a new operator in a function, you cannot prove that the object is really an instance of jQuery.Deferred. I think you need to go with Duck-Typing:

"When I see a bird that walks like a duck and swims like a duck and quack, like a duck, I call this bird a duck." - James Whitcomb Riley

Depending on which objects might otherwise be returned (which properties should be expected), check to see if there are any properties / methods:

 var x = getMysteriousObject(); if (x.promise) { // Deferred } else { // Not a deferred } 

You can view this check in detail:

 if ($.isFunction(x.promise)) { // Deferred } 

or (to distinguish pending objects and other implementations of the Promise interface)

 if (x.promise && x.resolve) { // Deferred } 
+29
Jun 09 2018-12-12T00:
source share

Inspired by Niko's answer , I created another implementation that would check if an object is deferred based on its properties , but also on the contents of these properties. I had to do this because my other object had a promise to promise.

 if (typeof value.resolve !== "function") { return false; } return String(value.resolve) === String($.Deferred().resolve); 
+1
Jul 10 '15 at 16:11
source share



All Articles