Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass Promises to jQuery.when(), or only Deferreds?

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:

  1. Can $.when() take either Promises or Deferreds? This seems to work in my testing.
  2. Is there a bug in the doc? I think it should say that $.when() takes Promises, not just Deferreds.
like image 385
Jonathan Aquino Avatar asked Apr 05 '16 18:04

Jonathan Aquino


People also ask

What is the difference between deferred and promise in JavaScript?

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.

What happens if no arguments are passed to jQuery's promise method?

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.

What is Deferreds in jQuery?

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.

What is a promise in jQuery?

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.”


1 Answers

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>
like image 62
guest271314 Avatar answered Sep 28 '22 04:09

guest271314