JavaScript使用Promise封裝Axios進(jìn)行高效開發(fā)
一、為什么要使用promise封裝
原生的axios書寫是這樣的:
axios({
url: 接口地址,
method:請求方法,
data:攜帶數(shù)據(jù),
}).then(res=>{
//請求接口成功的邏輯
}).catch(err=>{
//請求接口失敗的邏輯
})出現(xiàn)了這些問題:
(1)重復(fù)的地方特別多,顯得代碼不夠優(yōu)雅。
(2)后期一旦不使用axios,改用其它第三方訪問后端插件,一個(gè)個(gè)文件去修改,累死寶寶了。
(3)若是axios.then()里面在嵌套多次訪問后臺(tái)請求,業(yè)務(wù)變得極其復(fù)雜,且代碼不利于查看。
ES6中的promise橫空出世,解決了上面的痛點(diǎn)。axios本身也是一個(gè)promise,promise的出現(xiàn)就是為了解決地獄回調(diào)的問題(地獄回調(diào)至在請求后臺(tái)成功之后不斷嵌套多次異步請求),這就是為什么使用promise封裝axios請求。
二、如何封裝以及使用
本項(xiàng)目使用的工具以及知識(shí)點(diǎn): vue3+vite+axios+es6(promise)+es8(async,await),薄弱的地方建議先自學(xué)。
(1) vite搭建vue3項(xiàng)目控制臺(tái)所需指令
npm init @vitejs/app
//輸入項(xiàng)目名稱,選擇vue
cd ./項(xiàng)目名稱
npm i //安裝依賴
npm run dev //運(yùn)行項(xiàng)目
npm install axios //安裝axios依賴
(2)request.js 配置axios
import axios from 'axios'
const baseURL='http://localhost:8888/lostFound' //后臺(tái)接口的域名或者服務(wù)器地址
//請求攔截,會(huì)自動(dòng)在axios請求后端的時(shí)候添加請求頭,并將token添加到請求里面
const service =axios.interceptors.request.use(config => {
if (localStorage.getItem('token')) {
config.headers.token = localStorage.getItem('token');
}
return config;
}, error => { return Promise.reject(error) })
//響應(yīng)攔截,將后端傳回來的token放在localStorage緩存里
service.interceptors.response.use(response => {
localStorage.setItem("token", response.headers.token);
return response;
})
export default service(3)http.js中封裝axios
import service from './request'
//封裝axios請求
const myRequest = options => {
return new Promise((resolve, reject) => {
service({
url: options.url,
method: options.method || 'GET',
data: options.data || {},
params: options.params || {}
}).then(res => resolve(res)) //請求成功
.catch(err => reject(err)) //請求失敗
})
}
export default myRequest(4)在App.vue使用
<script setup>
import HelloWorld from './components/HelloWorld.vue'
import { myRequest } from './utils/http'
import { onMounted } from 'vue'
/**
* await后面跟一個(gè)promise,await可以省略很多.then的書寫,讓promise更加簡潔優(yōu)雅,await要在async函數(shù)體內(nèi)使用
*/
//get不攜帶參數(shù)獲取數(shù)據(jù)
const getWithNoParameters = async () => {
let res = await myRequest({ url: '/selectAllCategories'})
console.log('get不攜帶參數(shù)',res)
}
//get攜帶參數(shù)
const getWithParameters = async ()=>{
let params={
id:10
}
let res=await myRequest({url:'/selectFoundDetailById',params})
console.log('get攜帶參數(shù)',res)
}
//post請求方式
const post = async()=>{
let formData=new FormData()
formData.append('sno','1')
formData.append('password','1')
let res=await myRequest({url:'/login',method:'post',data:formData})
console.log('post:',res)
}
//生命周期鉤子函數(shù)
onMounted(() => {
getWithNoParameters()
getWithParameters()
post()
})
</script>
<template>
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Hello Vue 3 + Vite" />
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>(4)運(yùn)行結(jié)果:

(5)分析:
一個(gè)接口功能省下10行代碼,一個(gè)項(xiàng)目假設(shè)有40個(gè)接口,你就能省下400行冗余代碼了,感受到了精益求精的工匠精神。
三、拓展
//uniapp中也可以這樣封裝后端請求api
export myRequest= options =>{
return new Promise((resolve,reject)=>{
uni.request({
url: options.url,
method:options.method || 'GET',
data: options.data || {},
success: res=>{
//請求后臺(tái)成功
resolve(res)
},
fail: err=>{
//請求后臺(tái)失敗
reject(err)
}
}
})
})
}
//微信小程序中也可以這樣封裝后端請求api
export myRequest= options=>{
return new Promise((resolve,reject)=>{
wx.request({
url: options.url,
method:options.method || 'GET',
data: options.data || {},
success(res){
//請求后臺(tái)成功
resolve(res)
},
fail(err){
//請求后臺(tái)失敗
reject(err)
}
}
})
})
}到此這篇關(guān)于JavaScript使用Promise封裝Axios進(jìn)行高效開發(fā)的文章就介紹到這了,更多相關(guān)JS使用Promise封裝Axios內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用jscript實(shí)現(xiàn)二進(jìn)制讀寫腳本代碼
Reading And Writing Binary Files Using JScript正如我剛才推什么我能做的JScript中,我想出了對問題的二進(jìn)制文件。以下級的解決,這為小到中等大小的文件。我的部分包括這個(gè)職位在這里,因?yàn)槲壹磳⒏吨T表決,在一個(gè)職位約發(fā)送帶有附件的電郵通過JScript和它會(huì)使用這個(gè)二進(jìn)制文件碼來讀取,在二進(jìn)制附件檔案。2008-06-06
微信小程序購物車、父子組件傳值及calc的注意事項(xiàng)總結(jié)
這篇文章主要給大家介紹了關(guān)于微信小程序購物車、父子組件傳值及calc的注意事項(xiàng)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11
parseInt parseFloat js字符串轉(zhuǎn)換數(shù)字
轉(zhuǎn)換函數(shù)、強(qiáng)制類型轉(zhuǎn)換、利用js變量弱類型轉(zhuǎn)換。2010-08-08
微信小程序錄音實(shí)現(xiàn)功能并上傳(使用node解析接收)
在我們的日常開發(fā)中經(jīng)常會(huì)遇到錄音功能,并上傳到服務(wù)器,今天小編給大家分享微信小程序錄音功能實(shí)現(xiàn)并上傳錄音文件,使用node解析接收,需要的朋友可以參考下2020-02-02
javascript full screen 全屏顯示頁面元素的方法
要想讓頁面的某個(gè)元素全屏顯示,就像在網(wǎng)頁上看視頻的時(shí)候,可以全屏觀看一樣,該怎么實(shí)現(xiàn)呢2013-09-09
Bootstrap頁面標(biāo)題Page Header的實(shí)現(xiàn)方法
這篇文章主要為大家詳細(xì)介紹了Bootstrap頁面標(biāo)題Page Header的實(shí)現(xiàn)方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03
JS/HTML5游戲常用算法之路徑搜索算法 A*尋路算法完整實(shí)例
這篇文章主要介紹了JS/HTML5游戲常用算法之路徑搜索算法 A*尋路算法,結(jié)合完整實(shí)例形式分析了A*尋路算法的具體實(shí)現(xiàn)技巧,代碼備有詳盡的注釋便于理解,需要的朋友可以參考下2018-12-12

