I have a function that takes a single argument. I need to be able to tell if this argument is a jQuery Promise
or Deferred
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.
Here's an example of how I'd like my function to behave:
function displayMessage(message) {
if (message is a Promise or Deferred) {
message.then(displayMessage);
} else {
alert(message);
}
}
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.
This is important because if this were not the case, I would just be able to use jQuery.when
:
function displayMessage(message) {
jQuery.when(message).then(function(messageString) {
alert(messageString);
});
}
This would handle values and promises of values correctly...
displayMessage("hello"); // alerts "hello"
displayMessage(jQuery.Deferred().resolve("hello")); // alerts "hello"
...but once we get to promises of promises of values, it breaks down:
displayMessage(jQuery.Deferred().resolve(
jQuery.Deferred().resolve("hello")
)); // alerts "[object Object]"
jQuery.when
is able to tell if a value is promise, so apparently it is possible. How can I check?