本文內(nèi)容
fetch設(shè)置超時(shí)時(shí)間
所需知識(shí)點(diǎn):Promise.race
這次百米賽跑,我允許你先跑30秒,30秒內(nèi)你跑完,我輸,蛋糕歸你。
30秒內(nèi)跑不完,你輸,蛋糕歸我,賭不賭?!
延伸知識(shí)點(diǎn):Promise.all
這次百米賽跑,我們同時(shí)出發(fā),但是必須我們兩個(gè)人都到達(dá)終點(diǎn)才可以享用那美味的蛋糕,比不比?!
Promise.race 定義
接收一個(gè)數(shù)組,不同的是只要該數(shù)組中的 Promise 對(duì)象的狀態(tài)發(fā)生變化(無(wú)論是 resolve 還是 reject)該方法都會(huì)返回
根據(jù)這個(gè)就可以實(shí)現(xiàn)我們的超時(shí)時(shí)間設(shè)置
Promise.race:接收兩個(gè)promise對(duì)象,一個(gè)是本身的請(qǐng)求,一個(gè)是30秒后的發(fā)送promise的對(duì)象,
根據(jù)Promise.race的定義,會(huì)有兩種情況
IMG_3947.JPG
第一種返回超時(shí)Promise,即可處理超時(shí)
Promise.then((response) => '請(qǐng)求超時(shí)')
第一種返回請(qǐng)求Promise,即可處理數(shù)據(jù)
Promise.then((response) => '處理請(qǐng)求結(jié)果')
具體代碼
/**
* Created by chjwrr on 2017/7/24.
*/
const headers = {
"Content-Type": "multipart/form-data",
};
const timeOut = 30000;
const _fetch = (fetch_promise, timeout = timeOut) => {
let abort_fn = null;
// 超時(shí)promise
const abort_promise = new Promise((resolve, reject) => {
abort_fn = () => {
const err = new Error('timeout');
reject(err);
}
});
// 接收一個(gè)數(shù)組,只要該數(shù)組中的 Promise 對(duì)象的狀態(tài)發(fā)生變化(無(wú)論是 resolve 還是 reject)該方法都會(huì)返回
const abortable_promise = Promise.race([fetch_promise, abort_promise]);
// 30秒以后才發(fā)送超時(shí)promise,這時(shí)如果請(qǐng)求結(jié)束,則返回請(qǐng)求promise,如果還在請(qǐng)求,則返回超時(shí)promise
setTimeout(() => {
abort_fn()
}, timeout);
return abortable_promise;
};
const upLoadImageManager = (url, data, loadingCallBack, successCallBack, failCallBack) => {
loadingCallBack();
if (global.token) {
headers.Authorization = `Bearer ${global.token}`;
}
console.log('%c HTTP Request', 'color:blue');
console.log(`%c request url ${url}`, 'color:green');
console.log(`%c Request params ${JSON.stringify(data)}`, 'color:green');
const myFetch = fetch(url, {
method: 'POST',
headers,
body: data,
});
_fetch(myFetch, timeOut)
.then((response) => response.json())
.then((responseData) => {
successCallBack(responseData);
})
.catch((error) => {
failCallBack(error);
});
};
export {
upLoadImageManager,
};
延伸知識(shí)點(diǎn):Promise.all
Promise.all 可以接收一個(gè)元素為 Promise 對(duì)象的數(shù)組作為參數(shù),當(dāng)這個(gè)數(shù)組里面所有的 Promise 對(duì)象都變?yōu)?resolve 時(shí),該方法才會(huì)返回。
// 網(wǎng)絡(luò)代碼
var p1 = new Promise(function (resolve) {
setTimeout(function () {
resolve("Hello");
}, 3000); // 3秒后
});
var p2 = new Promise(function (resolve) {
setTimeout(function () {
resolve("World");
}, 1000); // 1秒后
});
Promise.all([p1, p2]).then(function (result) {
console.log(result); // ["Hello", "World"] 3秒后執(zhí)行,整合兩個(gè)pormise返回的數(shù)據(jù),返回?cái)?shù)組格式
});