How can I tell if an object is an Angular $q promise?

后端 未结 3 1982
天命终不由人
天命终不由人 2021-01-18 18:03

I have a pre-existing non-Angular API library in my project. It has a .request method which returns jQuery.Deferred promises. I created a simple Angular service

3条回答
  •  孤街浪徒
    2021-01-18 18:11

    Generally the better approach is to cast whatever object you do have into an Angular promise.

    The concept of assimilating thenables is part of the Promises/A+ specification. Most promise libraries have a way to do this. It's what allows for awesome interop between promise implementations and a uniform API.

    For this, $q uses .when :

    Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

    It uses the concept of thenables to convert a 'non trusted' promise into a $q promise.

    So all you have to do is

    var p = $q.when(value); // p is now always a $q promise
                            // if it already was one - no harm
    

提交回复
热议问题