Vue Promise的axios請(qǐng)求封裝詳解
現(xiàn)在應(yīng)該大部分公司都是前后端分離了。so,數(shù)據(jù)請(qǐng)求的封裝還是必須的。
為了實(shí)現(xiàn)向ios中block封裝請(qǐng)求的異步的效果,我采用JavaScript中promise這個(gè)對(duì)象。
var p1 = New promise((resolve,reject)=>{
var timeOut = Math.random() * 2;
log('set timeout to: ' + timeOut + ' seconds.');
setTimeout(function () {
if (timeOut < 1) {
log('call resolve()...');
resolve('200 OK');
}
else {
log('call reject()...');
reject('timeout in ' + timeOut + ' seconds.');
}
}, timeOut * 1000);
})
其中resolve,reject就相當(dāng)于是你定義了兩個(gè)block,然后把數(shù)據(jù)傳出去。
繼續(xù)往下看,緊接著上面的代碼
var p2 = p1.then(function (result) { //resolve 導(dǎo)出的數(shù)據(jù)
console.log('成功:' + result);
});
var p3 = p2.catch(function (reason) { //reject 導(dǎo)出的數(shù)據(jù)
console.log('失?。? + reason);
});
通過查閱資料還發(fā)現(xiàn)另外兩種用法,Promise.all 和 Promise.race這兩種。
var p1 = new Promise(function (resolve, reject) {
setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
setTimeout(resolve, 600, 'P2');
});
// 同時(shí)執(zhí)行p1和p2,并在它們都完成后執(zhí)行then:
Promise.all([p1, p2]).then(function (results) {
console.log(results); // 獲得一個(gè)Array: ['P1', 'P2']
});
這一種是p1 和 p2 都返回了數(shù)據(jù),才會(huì)執(zhí)行all后面的then函數(shù)。挺像ios中GCD的notify函數(shù)
第二種
var p1 = new Promise(function (resolve, reject) {
setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
setTimeout(resolve, 600, 'P2');
});
Promise.race([p1, p2]).then(function (result) {
console.log(result); // 'P1'
});
race跑步的意思,看誰跑得快,跑得慢的就被摒棄掉了。
上面這些是封裝的基礎(chǔ),下面來看具體應(yīng)用#
基于axios的請(qǐng)求封裝
//判斷請(qǐng)求環(huán)境來區(qū)分鏈接 生產(chǎn)環(huán)境和測(cè)試環(huán)境
const ajaxUrl = env === 'development' ?
'https://www.baidu.com' :
env === 'production' ?
'https://www.baidu.com' :
'https://www.baidu.com';
util.ajax = axios.create({
baseURL: ajaxUrl,
timeout: 30000
});
// options中包含著數(shù)據(jù)
export function axiosfetch(options) {
return new Promise((resolve, reject) => {
var token = window.localStorage.getItem('token') ? window.localStorage.getItem('token') : "";
var cid = window.localStorage.getItem('X-CID') ? window.localStorage.getItem('X-CID') : "";
// var language = window.localStorage.getItem('language') ? window.localStorage.getItem('language') : "";
var language = tools.getCookie('language')?tools.getCookie('language'): navigator.language;
language = language == "en-US" ? "en" : language ;
debug.log(language)
var params = tools.deepClone(options.params);//深拷貝
var sign_str = tools.sign(params); //簽名
const instance = axios.create({
baseURL: ajaxUrl,
timeout: 30000,
//instance創(chuàng)建一個(gè)axios實(shí)例,可以自定義配置,可在 axios文檔中查看詳情
//所有的請(qǐng)求都會(huì)帶上這些配置,比如全局都要用的身份信息等。
headers: { //所需的信息放到header頭中
// 'Content-Type': 'application/json',
"Authorization": token,
"X-CID":cid,
"X-LOCALE":language,
"X-SIGN":sign_str
},
// timeout: 30 * 1000 //30秒超時(shí)
});
let httpDefaultOpts = { //http默認(rèn)配置
method:options.method,
url: options.url,
timeout: 600000,
params:Object.assign(params),
data:qs.stringify(Object.assign(params)),
// headers: options.method=='get'?{
// 'X-Requested-With': 'XMLHttpRequest',
// "Accept": "application/json",
// "Content-Type": "application/json; charset=UTF-8",
// "Authorization": token
// }:{
// 'X-Requested-With': 'XMLHttpRequest',
// 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
// "Authorization": token
// }
}
if(options.method=='get'){ //判斷是get請(qǐng)求還是post請(qǐng)求
delete httpDefaultOpts.data
}else{
delete httpDefaultOpts.params
}
instance(httpDefaultOpts)
.then(response => {//then 請(qǐng)求成功之后進(jìn)行什么操作
debug.log('參數(shù):')
debug.log(options.params)
debug.log('響應(yīng):')
debug.log(response)
debug.log(response.data.errno)
if(response.data.errno == 401){
// alert(response.data.errmsg)
// window.location.href = window.location.protocol + "http://" +window.location.host + '/#/login'
return
}
if(response.data.errno == 400){
reject(response)
return
}
resolve(response)//把請(qǐng)求到的數(shù)據(jù)發(fā)到引用請(qǐng)求的地方
})
.catch(error => {
// console.log('請(qǐng)求異常信息=>:' + options.params + '\n' + '響應(yīng)' + error)
debug.log('請(qǐng)求異常信息=>:' + options.params + '\n' + '響應(yīng)' + error)
reject(error)
})
})
}
外面再包一層
export function getNodeDetailInfo(address) {
return axiosfetch({
url:api.nodeDetailAPI,//鏈接
method:"get",//get請(qǐng)求
params:{//數(shù)據(jù)
address:address
}
})
}
再下面就是實(shí)際應(yīng)用。
getNodeDetailInfo(address).then(res => {
var data = res.data.data;
}).catch(error => {
console.log(error, '請(qǐng)求失敗')
})
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
動(dòng)態(tài)實(shí)現(xiàn)element ui的el-table某列數(shù)據(jù)不同樣式的示例
這篇文章主要介紹了動(dòng)態(tài)實(shí)現(xiàn)element ui的el-table某列數(shù)據(jù)不同樣式的示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Vue鼠標(biāo)點(diǎn)擊事件和鍵盤事件舉例詳解
在Vue框架中我們經(jīng)常需要綁定各種JS事件,如"點(diǎn)擊事件"、"鼠標(biāo)移動(dòng)事件"、"鍵盤事件"等等,這篇文章主要給大家介紹了關(guān)于Vue鼠標(biāo)點(diǎn)擊事件和鍵盤事件的相關(guān)資料,需要的朋友可以參考下2024-01-01
element?el-tooltip實(shí)現(xiàn)自定義修改樣式
本文主要介紹了element?el-tooltip實(shí)現(xiàn)自定義修改樣式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
如何使用uniapp內(nèi)置組件webview消息傳遞詳解
uni-app的web-view組件用于在應(yīng)用中打開網(wǎng)頁,并支持應(yīng)用和網(wǎng)頁之間的消息傳遞,這篇文章主要介紹了如何使用uniapp內(nèi)置組件webview消息傳遞的相關(guān)資料,需要的朋友可以參考下2025-02-02
vue實(shí)現(xiàn)定義一個(gè)全局實(shí)例Vue.prototype
這篇文章主要介紹了vue實(shí)現(xiàn)定義一個(gè)全局實(shí)例Vue.prototype,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
element ui loading加載開啟與關(guān)閉方式
這篇文章主要介紹了element ui loading加載開啟與關(guān)閉方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08

