$.when()方法翻譯2
阿新 • • 發佈:2017-05-26
when immediate container red execute 保持 str keyword cancel
在復合deferreds中,其中一個失敗了,jQuery.when()立即啟動fail回調作為其主deferred。註意,在那個點有些deferreds或許仍舊處於未完成狀態。傳遞給fail回調的參數會為失敗的deferred匹配到fail回調的標記。這種情況下如果你需要執行額外的進程,諸如取消未完成的ajax請求,可以使用閉包保持對這個jqXHR對象的引用,並在fail回調中對其取消或檢驗。
mac不知道為何,文章字數一多,瀏覽器就重啟。只好分開寫了。
在一個事件中,deferred無完成值,對應的done參數將為undefined。如果一個deferred完成後僅一個值,讀經的參數將獲取到那個值。這樣,deferred完成值為復合值,那對應的參數將是一個數組。例子如下:見上。In the event a Deferred was resolved with no value, the corresponding doneCallback argument will be undefined. If a Deferred resolved to a single value, the corresponding argument will hold that value. In the case where a Deferred resolved to multiple values, the corresponding argument will be an array of those values. For example:
var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();
$.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
console.log( v1 ); // v1 is undefined
console.log( v2 ); // v2 is "abc"
console.log( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ]
});
d1.resolve();
d2.resolve( "abc" );
d3.resolve( 1, 2, 3, 4, 5 );
In the multiple-Deferreds case where one of the Deferreds is rejected, 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:
在兩個ajax請求成功後執行一個函數。(查看jQuery.ajax()文檔獲取完整的關於成功和錯誤狀態的ajax請求的文檔。)Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request).
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
// Each argument is an array with the following structure: [ data, statusText, jqXHR ]
var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
if ( /Whip It/.test( data ) ) {
alert( "We got what we came for!" );
}
});
Execute the function當兩個ajax請求成功後,執行函數myFunc,或者在二者之一出錯後執行myFailure.myFunc
when both ajax requests are successful, ormyFailure
if either one has an error.$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) )
.then( myFunc, myFailure );
$.when()方法翻譯2