封裝fetch的使用(包含超時處理)


// 1: 傳統fetch操作
fetch('http://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
//操作
})
.catch((error) => {
console.error(error);
});

// 2:使用promise封裝fetch ,異步執行
let common_url = 'http://192.168.1.1:8080/'; //服務器地址
let token = '';
/**
* @param {string} url 接口地址
* @param {string} method 請求方法:GET、POST,只能大寫
* @param {JSON} [params=''] body的請求參數,默認為空
* @return 返回Promise
*/
function fetchRequest(url, method, params = ''){
let header = {
"Content-Type": "application/json;charset=UTF-8",
"accesstoken":token //用戶登陸后返回的token,某些涉及用戶數據的接口需要在header中加上token
};
console.log('request url:',url,params); //打印請求參數
if(params == ''){ //如果網絡請求中帶有參數
return new Promise(function (resolve, reject) {
fetch(common_url + url, {
method: method,
headers: header
}).then((response) => response.json())
.then((responseData) => {
console.log('res:',url,responseData); //網絡請求成功返回的數據
resolve(responseData);
})
.catch( (err) => {
console.log('err:',url, err); //網絡請求失敗返回的數據
reject(err);
});
});
}else{ //如果網絡請求中沒有參數
return new Promise(function (resolve, reject) {
fetch(common_url + url, {
method: method,
headers: header,
body:JSON.stringify(params) //body參數,通常需要轉換成字符串后服務器才能解析
}).then((response) => response.json())
.then((responseData) => {
console.log('res:',url, responseData); //網絡請求成功返回的數據
resolve(responseData);
})
.catch( (err) => {
console.log('err:',url, err); //網絡請求失敗返回的數據
reject(err);
});
});
}
}
// 然后我們去使用這個封裝請求函數GET
fetchRequest('app/book','GET')
.then( res=>{
//請求成功
if(res.header.statusCode == 'success'){
//這里設定服務器返回的header中statusCode為success時數據返回成功
}else{
//服務器返回異常,設定服務器返回的異常信息保存在 header.msgArray[0].desc
console.log(res.header.msgArray[0].desc);
}
}).catch( err=>{
//請求失敗
})
//Post
let params = {
username:'admin',
password:'123456'
}
fetchRequest('app/signin','POST',params)
.then( res=>{
//請求成功
if(res.header.statusCode == 'success'){
//這里設定服務器返回的header中statusCode為success時數據返回成功

}else{
//服務器返回異常,設定服務器返回的異常信息保存在 header.msgArray[0].desc
console.log(res.header.msgArray[0].desc);
}
}).catch( err=>{
//請求失敗
})


// 3:加入超時處理,跟上面沒關系
/**
* 讓fetch也可以timeout
* timeout不是請求連接超時的含義,它表示請求的response時間,包括請求的連接、服務器處理及服務器響應回來的時間
* fetch的timeout即使超時發生了,本次請求也不會被abort丟棄掉,它在后台仍然會發送到服務器端,只是本次請求的響應內容被丟棄而已
* @param {Promise} fetch_promise fetch請求返回的Promise
* @param {number} [timeout=10000] 單位:毫秒,這里設置默認超時時間為10秒
* @return 返回Promise
*/
function timeout_fetch(fetch_promise,timeout = 10000) {
let timeout_fn = null;

//這是一個可以被reject的promise
let timeout_promise = new Promise(function(resolve, reject) {
//超時函數
timeout_fn = function() {
reject('timeout promise');
};
});

//這里使用Promise.race,以最快 resolve 或 reject 的結果來傳入后續綁定的回調,
//先執行fetch_promise 等待數據的返回,如果在定時后還沒返回 就執行超時函數
let abortable_promise = Promise.race([
fetch_promise,
timeout_promise
]);

setTimeout(function() {
timeout_fn();
}, timeout);

return abortable_promise ;
}

//應用:加入超時處理的fetchRequest網絡請求的使用方法跟沒加入超時處理一樣。 
let common_url = 'http://192.168.1.1:8080/'; //服務器地址
let token = ''; 
/**
* @param {string} url 接口地址
* @param {string} method 請求方法:GET、POST,只能大寫
* @param {JSON} [params=''] body的請求參數,默認為空
* @return 返回Promise
*/
function fetchRequest(url, method, params = ''){
let header = {
"Content-Type": "application/json;charset=UTF-8",
"accesstoken":token //用戶登陸后返回的token,某些涉及用戶數據的接口需要在header中加上token
};
console.log('request url:',url,params); //打印請求參數
if(params !== ''){ //如果網絡請求中帶有參數
return new Promise(function (resolve, reject) {
timeout_fetch(fetch(common_url + url, {
method: method,
headers: header
})).then((response) => response.json())
.then((responseData) => {
console.log('res:',url,responseData); //網絡請求成功返回的數據
resolve(responseData);
})
.catch( (err) => {
console.log('err:',url, err); //網絡請求失敗返回的數據 
reject(err);
});
});
}else{ //如果網絡請求中沒有參數
return new Promise(function (resolve, reject) {
timeout_fetch(fetch(common_url + url, {
method: method,
headers: header,
body:JSON.stringify(params) //body參數,通常需要轉換成字符串后服務器才能解析
})).then((response) => response.json())
.then((responseData) => {
console.log('res:',url, responseData); //網絡請求成功返回的數據
resolve(responseData);
})
.catch( (err) => {
console.log('err:',url, err); //網絡請求失敗返回的數據 
reject(err);
});
});
}
}
//參考文章http://imweb.io/topic/57c6ea35808fd2fb204eef63

 


免責聲明!

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



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