The documentation for jQuery.when() says that this function takes Deferreds. However, it also says later on that:
If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise...
which seems to imply that it can take Promises as well. But Promises are not Deferreds - they have a subset of the Deferred's methods. I guess you could say that a Deferred is a Promise, but a Promise is not a Deferred.
Questions:
The Deferred object has another important method named Promise (). This method returns an object with almost the same interface than the Deferred, but it only have the methods to attach callbacks and does not have the methods to resolve and reject.
If no arguments are passed to jQuery.when(), it will return a resolved Promise. If a single Deferred is passed to jQuery.when(), its Promise object (a subset of the Deferred methods) is returned by the method. Additional methods of the Promise object can be called to attach callbacks, such as deferred.then.
jQuery.when( deferreds )Returns: Promise. Description: Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events. Zero or more Thenable objects. If no arguments are passed to jQuery.when(), it will return a resolved Promise.
jQuery promise was released in mid-2011 as part of JQuery version 1.6. At the time, the definition provided was: “Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. jQuery objects can now return a Promise to observe when all animations on a collection have completed.”
What the documentation is attempting to convey is that $.when()
will accept a value that is neither a jQuery.Deferred()
, a jQuery.promise()
nor a Promise
; the value will be treated as a resolved jQuery.Deferred()
, which is described at next portion of sentence
If a single argument is passed to
jQuery.when()
and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.
For example
$.when(1).then(function(data) {
alert(data)
})
<script src="https://code.jquery.com/jquery-git.js">
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With