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.
-
version added: 1.5jQuery.when( deferreds )
-
deferredsZero or more Thenable objects.
-
jQuery.when()
, it will return a resolved Promise.
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
. When the Deferred is resolved or rejected, usually by the code that created the Deferred originally, the appropriate callbacks will be called. For example, the jqXHR object returned by jQuery.ajax()
is a Promise-compatible object and can be used this way:
1
2
3
|
|
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. The doneCallbacks are passed the original argument. In this case any failCallbacks you might set are never called since the Deferred is never rejected. For example:
1
2
3
|
|
jQuery.when()
will return a resolved promise.
1
2
3
|
|
jQuery.when()
, the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed. The method will resolve its master Deferred as soon as all the Deferreds resolve, or reject the master Deferred as soon as one of the Deferreds is rejected. If the master Deferred is resolved, the doneCallbacks for the master Deferred are executed. The arguments passed to the doneCallbacks provide the resolved values for each of the Deferreds, and matches the order the Deferreds were passed to jQuery.when()
. For example:
1
2
3
4
5
6
7
8
9
10
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
|
jQuery.when()
immediately fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still be unresolved at that point. The arguments passed to the failCallbacks match the signature of the failCallback for the Deferred that was rejected. If you need to perform additional processing for this case, such as canceling any unfinished Ajax requests, you can keep references to the underlying jqXHR objects in a closure and inspect/cancel them in the failCallback.
Examples:
Example 1
1
2
3
4
5
6
7
8
|
|
Example 2
myFunc
when both ajax requests are successful, or myFailure
if either one has an error.
1
2
|
|