jQuery.when()
Method
Example
A single argument is passed to $.when() and a callback function is executed.
$(function () {
$.when( { testing: 123 } ).done(
function(x) { alert(x.testing); } /* alerts "123" */
);
})
Definition and Usage
The $.when() function provides a way to execute callback functions based on one or more objects.
Tip: If a Deferred object is passed to jQuery.when, it returns its Promise object (a subset of the Deferred methods). You can continue to bind additional methods to the Promise object, such as defered.then. The corresponding callback functions will be called when the Deferred object is resolved or rejected (usually by the code that originally created the Deferred object).
Syntax
Parameter | Description |
---|---|
deferreds | Deferred type One or more Deferred objects, or plain JavaScript objects |
More Examples
If no arguments are passed, jQuery.when() will return a promise object in a resolved state.
Example
No arguments are passed, and a callback function is executed.
$(function () {
$.when().then(function( x ) {
alert( "I fired immediately" );
});
})
When multiple Deferred objects are passed to jQuery.when(), the method returns a new "master" Deferred object. It will resolve its master Deferred object only when all the Deferred objects are resolved. If any of the Deferred objects is rejected, the method will reject its master Deferred object. When the master object is resolved, the doneCallbacks will be executed.
Example
Passing multiple Deferred objects.
$(function () {
var d1 = $.Deferred();
var d2 = $.Deferred();
$.when( d1, d2 ).done(function ( v1, v2 ) {
alert( v1 ); // "Fish"
alert( v2 ); // "Pizza"
});
d1.resolve( "Fish" );
d2.resolve( "Pizza" );
})
If no values are passed to the resolved event of the Deferred object, the corresponding doneCallback parameters will be undefined. If a single value is passed to the resolved event of the Deferred object, the corresponding parameter will hold that value. If multiple values are passed to the resolved event of the Deferred object, the corresponding parameter will be an array of those values.
Example
Passing multiple Deferred objects with different types of values.
$(function () {
var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();
$.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
alert( v1 ); // v1 is undefined
alert( v2 ); // v2 is "abc"
alert( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ]
});
d1.resolve();
d2.resolve( "abc" );
d3.resolve( 1, 2, 3, 4, 5 );
})
In the case of multiple Deferred objects, if any of the Deferred objects is rejected, jQuery.when() will immediately call the failCallbacks of the "master" Deferred object.
Example
Calling failCallbacks when any of the Deferred objects is rejected.
$(function () {
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).then(function(data, textStatus, jqXHR){
alert(jqXHR.status); }, function(obj){
alert(obj.statusText);
});
})