發(fā)布于:2021-02-13 00:00:55
0
404
0
由于缺乏超時和請求取消,fetch API一開始就成為批評的目標(biāo)。盡管這些批評可能是公平的,也可能是不公平的,但你不能否認fetch API已經(jīng)非常棒了。就像我們一直做的那樣,如果一個功能缺失了,我們可以隨時補上它。
我最近一直在考慮在獲取超時中進行填充,并在此處找到了一個不錯的獲取/超時腳本。我對其進行了稍微修改,以防止fetch 調(diào)用then 和catch 回調(diào)執(zhí)行其任務(wù),因為我認為超時應(yīng)由填充程序的Promise處理:
const FETCH_TIMEOUT = 5000;
let didTimeOut = false;
new Promise(function(resolve, reject) {
const timeout = setTimeout(function() {
didTimeOut = true;
reject(new Error('Request timed out'));
}, FETCH_TIMEOUT);
fetch('https://davidwalsh.name/?xx1')
.then(function(response) {
// Clear the timeout as cleanup
clearTimeout(timeout);
if(!didTimeOut) {
console.log('fetch good! ', response);
resolve(response);
}
})
.catch(function(err) {
console.log('fetch failed! ', err);
// Rejection already happened with setTimeout
if(didTimeOut) return;
// Reject with error
reject(err);
});})
.then(function() {
// Request success and no timeout
console.log('good promise, no timeout! ');
})
.catch(function(err) {
// Error: response error, request timeout or runtime error
console.log('promise error! ', err);
});
將此代碼包裝在一個名為中的函數(shù)中fetchWithTimeout,這樣您就可以傳入超時并獲取URL /設(shè)置;由于人們喜歡以多種方式使用訪存,因此我選擇不創(chuàng)建通用函數(shù),而只是提供基本邏輯。
許多人認為超時應(yīng)該來自服務(wù)器,但是我們都知道前端開發(fā)人員并不總是能夠控制請求的兩端。如果您正在尋找提取請求超時代碼段,請點擊這里!