欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

用Promise解決多個異步Ajax請求導(dǎo)致的代碼嵌套問題(完美解決方案)

 更新時間:2017年02月27日 11:13:01   投稿:mrr  
這篇文章主要介紹了用Promise解決多個異步Ajax請求導(dǎo)致的代碼嵌套問題(完美解決方案),需要的朋友可以參考下

問題

前端小同學(xué)在做頁面的時候,犯了個常見的錯誤:把多個Ajax請求順序著寫下來了,而后面的請求,對前面請求的返回結(jié)果,是有依賴的。如下面的代碼所示:

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);
        }
      }
    });

以上代碼有兩個問題:

*首先就是執(zhí)行順序不能保證,action2很可能在action1返回之前就發(fā)出了,導(dǎo)致someData.attr1這個參數(shù)沒能正確傳出

*其次兩個ajax請求的代碼重復(fù)很嚴(yán)重

思路

  • 代碼重復(fù)的問題相對好解決,尤其是在自己的項目里,各種參數(shù)可以通過規(guī)范定死,封裝一個參數(shù)更少的ajax方法就好了
//url:地址
//data:數(shù)據(jù)對象,在函數(shù)內(nèi)部會轉(zhuǎn)化成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三個必要的參數(shù)要填,其他都定死了

  • 執(zhí)行順序的問題,可以把第二個請求放在第一個請求的回調(diào)里,形如:
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
   }
};

至此問題似乎解決得很完美,但可以想見,如果請求不止兩個,而是4、5個,同時還有其他異步操作(比如我們的頁面里有Vue對象的初始化),相互之間有依賴關(guān)系,光是這樣層層疊疊的括號嵌套,就已經(jīng)讓人頭暈了。

需要找到一種方法,讓異步調(diào)用的表達(dá)看起來像同步調(diào)用一樣。

正好最近看了阮一峰老師關(guān)于ES6的書,而且用戶也沒有強(qiáng)硬要求兼容IE瀏覽器,于是就選擇了Promise的方案

解決方案

  • 引入Promise

其實現(xiàn)代瀏覽器都已經(jīng)內(nèi)置支持了Promise,連第三方庫都不需要了,只有IE不行,放棄了

  • 改造ajax封裝函數(shù),在成功的時候調(diào)用resolve(),失敗的時候調(diào)用reject(),并且返回Promise對象
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;
}
  • 修改調(diào)用端
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
)

以上所述是小編給大家介紹的用Promise解決多個異步Ajax請求導(dǎo)致的代碼嵌套問題(完美解決方案),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論