fetch的timeout超時設置


最近在一個項目里面需要做請求超時的處理,但是原本接口請求用的是fetch,而且fetch不支持超時處理,為了有較小的改動就能夠實現超時不得不去自己封裝或者找第三方插件解決這個問題,在看了一些開源插件后(如fetch-timeout),自己封裝了一個fetch_timeout。
首先介紹下思路,核心是利用建立一個超時的abortPromise和接口請求的fetchPromise傳入 Promise.race() 來進行處理,哪個Promise先返回結果則最終輸出這個Promise的返回值。具體如下
 
創建abortPromise
let abort = null; let abortPromise = new Promise((resolve, reject) => { abort = () => { return reject({ code: 504, message: "請求超時!" }); }; });

 

創建fetchPromise
let fetchPromise=fetch(url,prama)

 

傳入Promise.race,設置一個定時器用於觸發abortPromise內部函數abort返回一個Promise結果,然后返回最后輸出的Promise為 resultPromise
// 最快出結果的promise 作為結果
let resultPromise = Promise.race([fecthPromise, abortPromise]); setTimeout(() => { abort(); }, timeout); return resultPromise;
 
封裝
/** * 實現fetch的timeout 功能 * @param {object} fecthPromise fecth * @param {Number} timeout 超時設置,默認5000ms * */
 
function fetch_timeout(fecthPromise, timeout = 5000) { let abort = null; let abortPromise = new Promise((resolve, reject) => { abort = () => { return reject({ code: 504, message: "請求超時!" }); }; }); // 最快出結果的promise 作為結果
  let resultPromise = Promise.race([fecthPromise, abortPromise]); setTimeout(() => { abort(); }, timeout); returnresultPromise.then(res => {
      clearTimeout(timeout);
      return res;
   });
} export default fetch_timeout;

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM