用Promise解決多個異步Ajax請求致使的代碼嵌套問題

問題

前端小同窗在作頁面的時候,犯了個常見的錯誤:把多個Ajax請求順序着寫下來了,然後面的請求,對前面請求的返回結果,是有依賴的。以下面的代碼所示:html

var someData;
$.ajax({
            url: '/prefix/entity1/action1',
            type: 'GET' ,
            async: true,
            contentType: "application/json",
            success: function (resp) {
                //do something on response
               someData.attr1 = resp.attr1;
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //在這個頁面裏,全部的請求的錯誤都作一樣的處理
                if (XMLHttpRequest.status == "401") {
                    window.location.href = '/login.html';
                } else {
                    alert(XMLHttpRequest.responseText);
                }
            }
        });

$.ajax({
            url: '/prefix/entity2/action2',
            type: 'POST' ,
            dataType: "json",
            data: JSON.stringify(someData),
            async: true,
            contentType: "application/json",
            success: function (resp) {
                //do something on response
             },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //在這個頁面裏,全部的請求的錯誤都作一樣的處理
                if (XMLHttpRequest.status == "401") {
                    window.location.href = '/login.html';
                } else {
                    alert(XMLHttpRequest.responseText);
                }
            }
        });

以上代碼有兩個問題:
*首先就是執行順序不能保證,action2極可能在action1返回以前就發出了,致使someData.attr1這個參數沒能正確傳出
*其次兩個ajax請求的代碼重複很嚴重前端

思路

  • 代碼重複的問題相對好解決,尤爲是在本身的項目裏,各類參數能夠經過規範定死,封裝一個參數更少的ajax方法就行了ajax

//url:地址
//data:數據對象,在函數內部會轉化成json串,若是沒傳,表示用GET方法,若是傳了,表示用POST方法
function ajax(url, data, callback) {
        $.ajax({
            url: url,
            type: data == null ? 'GET' : 'POST',
            dataType: "json",
            data: data == null ? '' : JSON.stringify(data),
            async: true,
            contentType: "application/json",
            success: function (resp) {
                callback(resp);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.status == "401") {
                    window.parent.location = '/enterprise/enterprise_login.html';
                    self.location = '/enterprise/enterprise_login.html';
                } else {
                    alert(XMLHttpRequest.responseText);
                }
            }
        });
}

這樣只有url,data和callback三個必要的參數要填,其餘都定死了json

  • 執行順序的問題,能夠把第二個請求放在第一個請求的回調裏,形如:瀏覽器

ajax('/prefix/entity1/action1',null, function(resp){
     //do something on response
     someData.attr1 = resp.attr1;
     ajax('/prefix/entity2/action2', someData, function(resp){
          //do something on response
     }
};

至此問題彷佛解決得很完美,但能夠想見,若是請求不止兩個,而是四、5個,同時還有其餘異步操做(好比咱們的頁面裏有Vue對象的初始化),相互之間有依賴關係,光是這樣層層疊疊的括號嵌套,就已經讓人頭暈了。app

須要找到一種方法,讓異步調用的表達看起來像同步調用同樣。異步

正好最近看了阮一峯老師關於ES6的書,並且用戶也沒有強硬要求兼容IE瀏覽器,因而就選擇了Promise的方案async

解決方案

  • 引入Promise
    其實現代瀏覽器都已經內置支持了Promise,連第三方庫都不須要了,只有IE不行,放棄了函數

  • 改造ajax封裝函數,在成功的時候調用resolve(),失敗的時候調用reject(),而且返回Promise對象url

function ajax(url, data, callback) {
    var p = new Promise(function (resolve, reject) {
        $.ajax({
            url: url,
            type: data == null ? 'GET' : 'POST',
            dataType: "json",
            data: data == null ? '' : JSON.stringify(data),
            async: true,
            contentType: "application/json",
            success: function (resp) {
                callback(resp);
                resolve();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.status == "401") {
                    window.parent.location = '/enterprise/enterprise_login.html';
                    self.location = '/enterprise/enterprise_login.html';
                } else {
                    alert(XMLHttpRequest.responseText);
                }
                reject();
            }
        });
    });
    return p;
}
  • 修改調用端

ajax('/prefix/entity1/action1',null, function(resp){
     //do something on response
     someData.attr1 = resp.attr1;
}).then(
     ajax('/prefix/entity2/action2', someData, function(resp){
          //do something on response
     }
).then(
     initVue() ;
).then(
     //do  something else
)

至此完美解決。


經@miroki 提醒,發現Jquery從1.5版開始,返回的就是thenable對象了,那麼ajax函數能夠直接返回$.ajax()的返回值

相關文章
相關標籤/搜索