中文字幕一区二区人妻电影,亚洲av无码一区二区乱子伦as ,亚洲精品无码永久在线观看,亚洲成aⅴ人片久青草影院按摩,亚洲黑人巨大videos

JavaScript超時(shí)獲取

發(fā)布于:2021-02-13 00:00:55

0

404

0

JavaScript 超時(shí)

由于缺乏超時(shí)和請(qǐng)求取消,fetch API一開始就成為批評(píng)的目標(biāo)。盡管這些批評(píng)可能是公平的,也可能是不公平的,但你不能否認(rèn)fetch API已經(jīng)非常棒了。就像我們一直做的那樣,如果一個(gè)功能缺失了,我們可以隨時(shí)補(bǔ)上它。

我最近一直在考慮在獲取超時(shí)中進(jìn)行填充,并在此處找到了一個(gè)不錯(cuò)的獲取/超時(shí)腳本。我對(duì)其進(jìn)行了稍微修改,以防止fetch 調(diào)用then 和catch 回調(diào)執(zhí)行其任務(wù),因?yàn)槲艺J(rèn)為超時(shí)應(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);
   });

將此代碼包裝在一個(gè)名為中的函數(shù)中fetchWithTimeout,這樣您就可以傳入超時(shí)并獲取URL /設(shè)置;由于人們喜歡以多種方式使用訪存,因此我選擇不創(chuàng)建通用函數(shù),而只是提供基本邏輯。

許多人認(rèn)為超時(shí)應(yīng)該來自服務(wù)器,但是我們都知道前端開發(fā)人員并不總是能夠控制請(qǐng)求的兩端。如果您正在尋找提取請(qǐng)求超時(shí)代碼段,請(qǐng)點(diǎn)擊這里!