How can I determine if a jQuery object is deferred?

后端 未结 3 1796
醉梦人生
醉梦人生 2020-12-11 00:21

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?

3条回答
  •  北海茫月
    2020-12-11 00:50

    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
    }
    

提交回复
热议问题