1. 程式人生 > >jquery的 非同步載入$.when

jquery的 非同步載入$.when

$.when()方法

$.when()接受多個deferred物件作為引數,當它們全部執行成功後,才呼叫resolved狀態的回撥函式,但只要其中有一個失敗,就呼叫rejected狀態的回撥函式。它相當於將多個非同步操作,合併成一個。實質上,when方法為多個deferred物件,返回一個單一的promise物件

$.when(
    $.ajax( "/main.php" ),
    $.ajax( "/modules.php" ),
    $.ajax( "/lists.php" )
).then(successFunc, failureFunc);

上面程式碼表示,要等到三個ajax操作都結束以後,才執行then方法指定的回撥函式。

when方法裡面要執行多少個操作,回撥函式就有多少個引數,對應前面每一個操作的返回結果。

 

$.when(
    $.ajax( "/main.php" ),
    $.ajax( "/modules.php" ),
    $.ajax( "/lists.php" )
).then(function (resp1, resp2, resp3){
    console.log(resp1);
    console.log(resp2);
    console.log(resp3);
});

上面程式碼的回撥函式有三個引數,resp1、resp2和resp3,依次對應前面三個ajax操作的返回結果。

如果when方法的引數不是deferred或promise物件,則直接作為回撥函式的引數。

上面如果,返回值是一個變數,則直接拿取變數,並且是按照$.when裡面的排序,按照順序返回資料的

 

 

jquery的 defer解決地獄回撥(非同步請求,回撥裡面巢狀ajax請求的這種)

對於$.ajax請求來說,如果層級比較多,程式看起來會比較亂,而為了解決這種問題,才有了$when...done...fail...then的封裝,它將$.ajax這巢狀結構轉成了順序平行的結果,向下面的$.ajax寫法,看起來很亂

$.ajax({
url: "/home/GetProduct",
dataType: "JSON",
type: "GET",
success: function (data) {
$.ajax({
url: "/home/GetProduct",
dataType: "JSON",
type: "GET",
success: function (data) {
$.ajax({
url: "/home/GetProduct",
dataType: "JSON",
type: "GET",
success: function (data) {
}
}
}

而它實現的功能無非就是外層執行完成後,去執行內層的程式碼程式碼,看下面的$.when寫法,就清晰多了

$.when($.ajax({
url: "/home/GetProduct",
dataType: "JSON",
type: "GET",
success: function (data) {
alert(JSON.stringify(data));
}
})).done(function (data) {
alert(data[0].Name);
}).done(function (data) {
alert(data[1].Name);
}).fail(function () {
alert("程式出現錯誤!");
}).then(function (data) {
alert("程式執行完成");
});