title: How can I tell if an object is a jQuery Promise/Deferred?
body: <p>I have a function that takes a single argument. I need to be able to tell if this argument is a jQuery <code>Promise</code> or <code>Deferred</code> object. If not, then the value may be of any type and have any properties, so it's not safe to just just for the presence of the promise methods.</p>
  
  <p>Here's an example of how I'd like my function to behave:</p>
  
  <pre><code>function displayMessage(message) {
    if (message is a Promise or Deferred) {
      message.then(displayMessage);
    } else {
      alert(message);
    }
  }
  </code></pre>
  
  <p>Notice the recursive handling of promises: if a promise is resolved with another promise value we don't display it, we wait for it to be resolved. If it returns yet another promise, repeat.</p>
  
  <hr>
  
  <p>This is important because if this were not the case, I would just be able to use <a href="http://api.jquery.com/jQuery.when/" rel="noreferrer"><code>jQuery.when</code></a>:</p>
  
  <pre><code>function displayMessage(message) {
    jQuery.when(message).then(function(messageString) {
      alert(messageString);
    });
  }
  </code></pre>
  
  <p>This would handle values and promises of values correctly...</p>
  
  <pre><code>displayMessage("hello");                            // alerts "hello"
  displayMessage(jQuery.Deferred().resolve("hello")); // alerts "hello"
  </code></pre>
  
  <p>...but once we get to promises of promises of values, it breaks down:</p>
  
  <pre><code>displayMessage(jQuery.Deferred().resolve(
    jQuery.Deferred().resolve("hello")
  ));                                                 // alerts "[object Object]"
  </code></pre>
  
  <hr>
  
  <p><code>jQuery.when</code> is able to tell if a value is promise, so apparently it is possible. How can I check?</p>