問題
前端小同學在做頁面的時候,犯了個常見的錯誤:把多個Ajax請求順序着寫下來了,而后面的請求,對前面請求的返回結果,是有依賴的。如下面的代碼所示:
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方法就好了
1 //url:地址 2 //data:數據對象,在函數內部會轉化成json串,如果沒傳,表示用GET方法,如果傳了,表示用POST方法 3 function ajax(url, data, callback) { 4 $.ajax({ 5 url: url, 6 type: data == null ? 'GET' : 'POST', 7 dataType: "json", 8 data: data == null ? '' : JSON.stringify(data), 9 async: true, 10 contentType: "application/json", 11 success: function (resp) { 12 callback(resp); 13 }, 14 error: function (XMLHttpRequest, textStatus, errorThrown) { 15 if (XMLHttpRequest.status == "401") { 16 window.parent.location = '/enterprise/enterprise_login.html'; 17 self.location = '/enterprise/enterprise_login.html'; 18 } else { 19 alert(XMLHttpRequest.responseText); 20 } 21 } 22 }); 23 }
- 這樣只有url,data和callback三個必要的參數要填,其他都定死了
- 執行順序的問題,可以把第二個請求放在第一個請求的回調里,形如:
1 ajax('/prefix/entity1/action1',null, function(resp){ 2 //do something on response 3 someData.attr1 = resp.attr1; 4 ajax('/prefix/entity2/action2', someData, function(resp){ 5 //do something on response 6 } 7 };
至此問題似乎解決得很完美,但可以想見,如果請求不止兩個,而是4、5個,同時還有其他異步操作(比如我們的頁面里有Vue對象的初始化),相互之間有依賴關系,光是這樣層層疊疊的括號嵌套,就已經讓人頭暈了。
需要找到一種方法,讓異步調用的表達看起來像同步調用一樣。
正好最近看了阮一峰老師關於ES6的書,而且用戶也沒有強硬要求兼容IE瀏覽器,於是就選擇了Promise的方案
解決方案
-
引入Promise
其實現代瀏覽器都已經內置支持了Promise,連第三方庫都不需要了,只有IE不行,放棄了 -
改造ajax封裝函數,在成功的時候調用resolve(),失敗的時候調用reject(),並且返回Promise對象
1 function ajax(url, data, callback) { 2 var p = new Promise(function (resolve, reject) { 3 $.ajax({ 4 url: url, 5 type: data == null ? 'GET' : 'POST', 6 dataType: "json", 7 data: data == null ? '' : JSON.stringify(data), 8 async: true, 9 contentType: "application/json", 10 success: function (resp) { 11 callback(resp); 12 resolve(); 13 }, 14 error: function (XMLHttpRequest, textStatus, errorThrown) { 15 if (XMLHttpRequest.status == "401") { 16 window.parent.location = '/enterprise/enterprise_login.html'; 17 self.location = '/enterprise/enterprise_login.html'; 18 } else { 19 alert(XMLHttpRequest.responseText); 20 } 21 reject(); 22 } 23 }); 24 }); 25 return p; 26 }
- 修改調用端
1 ajax('/prefix/entity1/action1',null, function(resp){ 2 //do something on response 3 someData.attr1 = resp.attr1; 4 }).then( 5 ajax('/prefix/entity2/action2', someData, function(resp){ 6 //do something on response 7 } 8 ).then( 9 initVue() ; 10 ).then( 11 //do something else 12 )
至此完美解決。
經@miroki 提醒,發現Jquery從1.5版開始,返回的就是thenable對象了,那么ajax函數可以直接返回$.ajax()的返回值