本文參考了Fetch進(jìn)階指南
緣起
fetch網(wǎng)絡(luò)請(qǐng)求沒有timeout機(jī)制气筋,也沒有about機(jī)制拆内。
而日常開發(fā)過程中,必定要對(duì)請(qǐng)求超時(shí)做處理宠默,也要及時(shí)終止不需要的網(wǎng)絡(luò)請(qǐng)求麸恍。
所以,就需要自己封裝fetch來實(shí)現(xiàn)搀矫。
實(shí)現(xiàn)
Promise.race(promise1,promise2,...) 方法返回一個(gè)Promise對(duì)象, 只要參數(shù)中任意一個(gè)Promise 被 resolve 或者 reject 后, 外部的Promise 就會(huì)以相同的值被 resolve 或者 reject.
import React, {Component} from 'react';
/**
* 使用Promise封裝Fetch抹沪,具有網(wǎng)絡(luò)超時(shí)刻肄、請(qǐng)求終止的功能
*/
class NetUtil extends Component {
static baseUrl = "http://xxxx:81/api/";
static token = '';
/**
* post請(qǐng)求
* url : 請(qǐng)求地址
* data : 參數(shù)(Json對(duì)象)
* callback : 回調(diào)函數(shù)
* */
static fetch_request(url, method, params = '') {
let header = {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
'accesstoken': NetUtil.token,
}
let promise = null;
if (params == '') {
promise = new Promise((resolve, reject) => {
fetch(NetUtil.baseUrl + url, {method: method, headers: header})
.then(response => response.json())
.then(responseData => resolve(responseData))
.then(err => reject(err))
})
} else {
promise = new Promise((resolve, reject) => {
fetch(NetUtil.baseUrl + url, {method: method, headers: header, body: JSON.stringify(params)})
.then(response => response.json())
.then(responseData => resolve(responseData))
.then(err => reject(err))
})
}
return NetUtil.warp_fetch(promise);
}
/**
* 創(chuàng)建兩個(gè)promise對(duì)象,一個(gè)負(fù)責(zé)網(wǎng)絡(luò)請(qǐng)求采够,另一個(gè)負(fù)責(zé)計(jì)時(shí)肄方,如果超過指定時(shí)間,就會(huì)先回調(diào)計(jì)時(shí)的promise蹬癌,代表網(wǎng)絡(luò)超時(shí)权她。
* @param {Promise} fetch_promise fetch請(qǐng)求返回的Promise
* @param {number} [timeout=10000] 單位:毫秒,這里設(shè)置默認(rèn)超時(shí)時(shí)間為10秒
* @return 返回Promise
*/
static warp_fetch(fetch_promise, timeout = 10000) {
let timeout_fn = null;
let abort = null;
//創(chuàng)建一個(gè)超時(shí)promise
let timeout_promise = new Promise(function (resolve, reject) {
timeout_fn = function () {
reject('網(wǎng)絡(luò)請(qǐng)求超時(shí)');
};
});
//創(chuàng)建一個(gè)終止promise
let abort_promise = new Promise(function (resolve, reject) {
abort = function () {
reject('請(qǐng)求終止');
};
});
//競(jìng)賽
let abortable_promise = Promise.race([
fetch_promise,
timeout_promise,
abort_promise,
]);
//計(jì)時(shí)
setTimeout(timeout_fn, timeout);
//終止
abortable_promise.abort = abort;
return abortable_promise;
}
}
export default NetUtil;