From 3e1b8278248652502125f1240e6b209c87eafdc2 Mon Sep 17 00:00:00 2001
From: Aurelio De Rosa If no arguments are passed to If a single Deferred is passed to In the previous example, When a single Deferred, Promise, or Promise-compatible object is passed to If a single argument is passed to 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:
+
-$.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
- alert( jqXHR.status ); // Alerts 200
+$.when( $.ajax( "test.aspx" ), $.ajax( "page.aspx" ) ).then(function( res1, res2 ) {
+ alert( res1[2].status ); // Alerts 200
+})
+.fail(function( err1, err2 ) {
+ alert( err1.status );
});
res1
and res2
are arrays containing three values: data
, textStatus
, and jqXHR
. It is adviced to always provide a callback to handle errors through the use of deferred.fail()
or the second parameter of deferred.then()
.jQuery.when()
, an argument for each of the returned value is provided to the doneCallback
instead of a single argument containing an array of values. It is suggested not to rely on this behavior because it is considered an anti-pattern and it will change in the upcoming versions of jQuery, starting with version 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:
$.when( { testing: 123 } ).done(function( x ) {