問(wèn)題
前端小同學(xué)在做頁(yè)面的時(shí)候,犯了個(gè)常見(jiàn)的錯(cuò)誤:把多個(gè)Ajax請(qǐng)求順序著寫(xiě)下來(lái)了,而后面的請(qǐng)求,對(duì)前面請(qǐng)求的返回結(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) {
//在這個(gè)頁(yè)面里,所有的請(qǐng)求的錯(cuò)誤都做同樣的處理
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) {
//在這個(gè)頁(yè)面里,所有的請(qǐng)求的錯(cuò)誤都做同樣的處理
if (XMLHttpRequest.status == "401") {
window.location.href = '/login.html';
} else {
alert(XMLHttpRequest.responseText);
}
}
});
以上代碼有兩個(gè)問(wèn)題:
*首先就是執(zhí)行順序不能保證,action2很可能在action1返回之前就發(fā)出了,導(dǎo)致someData.attr1這個(gè)參數(shù)沒(méi)能正確傳出
*其次兩個(gè)ajax請(qǐng)求的代碼重復(fù)很?chē)?yán)重
思路
- 代碼重復(fù)的問(wèn)題相對(duì)好解決,尤其是在自己的項(xiàng)目里,各種參數(shù)可以通過(guò)規(guī)范定死,封裝一個(gè)參數(shù)更少的ajax方法就好了
//url:地址
//data:數(shù)據(jù)對(duì)象,在函數(shù)內(nèi)部會(huì)轉(zhuǎn)化成json串,如果沒(méi)傳,表示用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三個(gè)必要的參數(shù)要填,其他都定死了
- 執(zhí)行順序的問(wèn)題,可以把第二個(gè)請(qǐng)求放在第一個(gè)請(qǐng)求的回調(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
}
};
至此問(wèn)題似乎解決得很完美,但可以想見(jiàn),如果請(qǐng)求不止兩個(gè),而是4、5個(gè),同時(shí)還有其他異步操作(比如我們的頁(yè)面里有Vue對(duì)象的初始化),相互之間有依賴關(guān)系,光是這樣層層疊疊的括號(hào)嵌套,就已經(jīng)讓人頭暈了。
需要找到一種方法,讓異步調(diào)用的表達(dá)看起來(lái)像同步調(diào)用一樣。
正好最近看了阮一峰老師關(guān)于ES6的書(shū),而且用戶也沒(méi)有強(qiáng)硬要求兼容IE瀏覽器,于是就選擇了Promise的方案
解決方案
其實(shí)現(xiàn)代瀏覽器都已經(jīng)內(nèi)置支持了Promise,連第三方庫(kù)都不需要了,只有IE不行,放棄了
- 改造ajax封裝函數(shù),在成功的時(shí)候調(diào)用resolve(),失敗的時(shí)候調(diào)用reject(),并且返回Promise對(duì)象
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
)
以上所述是小編給大家介紹的用Promise解決多個(gè)異步Ajax請(qǐng)求導(dǎo)致的代碼嵌套問(wèn)題(完美解決方案),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
您可能感興趣的文章:- 在vue項(xiàng)目中promise解決回調(diào)地獄和并發(fā)請(qǐng)求的問(wèn)題
- promise處理多個(gè)相互依賴的異步請(qǐng)求(實(shí)例講解)
- js利用遞歸與promise 按順序請(qǐng)求數(shù)據(jù)的方法
- 利用Promise自定義一個(gè)GET請(qǐng)求的函數(shù)示例代碼
- JavaScript如何利用Promise控制并發(fā)請(qǐng)求個(gè)數(shù)