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?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
Since jQuery Deferreds are created by copying the methods of a hidden object instead of calling the new operator on a function, you cannot proof that the object is indeed an instance of jQuery.Deferred. I think you're gonna need to go with Duck-Typing:
Depending on what objects might otherwise be returned (what properties must be expected), check if particular properties / methods are present:
You can detailed this check if required:
or (to distinguish between Deferred objects and other implementations of the Promise interface)
Inspired by Niko's answer, I created another implementation that would check if an object is a deferred based on the name of it's properties but also on the content of those properties. I had to do so since an other object of mine had a property named promise.
Depending on your use case, you could also use
jQuery.when
[1]:With
jQuery.when
you can treat your mysterious object always as deferred:[1] http://api.jquery.com/jQuery.when/