How can I determine if a jQuery object is deferred?

血红的双手。 提交于 2019-11-28 11:52:17

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/

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:

"When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck." – James Whitcomb Riley

Depending on what objects might otherwise be returned (what properties must be expected), check if particular properties / methods are present:

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

You can detailed this check if required:

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

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

if (x.promise && x.resolve) {
    // Deferred
}
The_Black_Smurf

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.

if (typeof value.resolve !== "function") {
  return false;
}
return String(value.resolve) === String($.Deferred().resolve);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!