前端同事做頁面時犯了一個很常見的錯誤:把多個 Ajax 請求「順序寫下來」,以為它們會依序執行,而後面的請求其實依賴前面請求的結果。
var someData;
$.ajax({
url: '/prefix/entity1/action1',
type: 'GET',
async: true,
contentType: "application/json",
success: function (resp) {
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);
}
}
});
這段程式有兩個問題:
someData.attr1 是 undefined。在自己專案裡,參數與錯誤處理都可以透過規範定死,因此封裝一個參數更少的 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 三個參數要填,其他都固定下來了。
把第二個請求放進第一個請求的回呼裡:
ajax('/prefix/entity1/action1', null, function (resp) {
someData.attr1 = resp.attr1;
ajax('/prefix/entity2/action2', someData, function (resp) {
// do something on response
});
});
問題看似解決了。但可以想見,如果請求不是兩個而是四五個,同時還有其他非同步操作(例如 Vue 實例的初始化)彼此有依賴關係,這種層層疊疊的括號已經讓人頭暈——這就是所謂的 callback 地獄。
真正需要的是:讓非同步呼叫的寫法看起來像同步呼叫。
現代瀏覽器都已內建 Promise,不需要引入第三方庫(IE 不支援,若必須相容就得靠 polyfill)。
成功時呼叫 resolve()、失敗時呼叫 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;
}
用 then 串起順序,可讀性立刻不同:
ajax('/prefix/entity1/action1', null, function (resp) {
someData.attr1 = resp.attr1;
})
.then(function () {
return ajax('/prefix/entity2/action2', someData, function (resp) {
// do something on response
});
})
.then(function () {
return initVue();
})
.then(function () {
// do something else
});
注意每個 then 中要 return 下一個 Promise,否則鏈接會斷掉、順序又會失準。若再把 callback 改成用 resolve(resp) 把資料往下一個 then 傳,並搭配 async/await,程式碼會更接近同步風格的直敘句:
async function init() {
const r1 = await ajax('/prefix/entity1/action1', null);
someData.attr1 = r1.attr1;
const r2 = await ajax('/prefix/entity2/action2', someData);
await initVue();
}
以上就是用 Promise 解決多個非同步 Ajax 請求造成巢狀問題的完整做法,希望對大家有所幫助。