在vue項目中promise解決回調(diào)地獄和并發(fā)請求的問題
場景需求:
需要同時請求5個接口
都請求成功后執(zhí)行下一步操作
解決方法:
定義一個變量i=5,請求成功一個接口,讓i–,直到i=0時執(zhí)行下一個操作,否則不執(zhí)行
axios.all 并發(fā)請求,.then(axios.spread(function(callback1, callback2)){})
promise.all 并發(fā)請求,.then(function([callback1, callback2]){})
1、回調(diào)地獄:
函數(shù)作為參數(shù)層層嵌套
代替的為.then的鏈式操作
2、promise.all并發(fā)請求
引入接口
import {getSellerDetail} from '../../api/seller'
import {getMemberCardInfo} from '../../api/pay_online/index'
數(shù)據(jù)處理
1. 創(chuàng)建一個Promise實例,獲取數(shù)據(jù)
2. 并把數(shù)據(jù)傳遞給處理函數(shù)resolve和reject
3. promise在聲明時就執(zhí)行了
created(){
if (this.$route.query.type){
this.type = this.$route.query.type;
this.sellerId = this.$route.query.targetId;
this.initApi()
}
},
methods: {
initApi(){
`// 商戶信息`
let SellerDetailApi = new Promise((resolve, reject) => {
getSellerDetail(this.sellerId).then( res => {
resolve(res) // resolve(res.data)
}).catch( err => {
reject(res)
})
})
`// 會員卡信息`
let MemberCardInfoApi = new Promise((resolve, reject) => {
getMemberCardInfo(this.sellerId, this.payMoney).then( res => {
resolve(res) // resolve(res.data)
}).catch( err => {
reject(res)
})
})
`// Promise的all方法,等數(shù)組中的所有promise對象都完成執(zhí)行`
Promise.all([SellerDetailApi, MemberCardInfoApi]).then( res => {
this.loading = false;
// 商戶信息
this.detail = res[0].data.detail;
this.sellerPic = this.detail.picture;
this.sellerName = this.detail.name;
this.discount = this.detail.discount;
// 會員卡信息
this.cardDetail = res[1].data;
this.balance = this.cardDetail.balance; //余額
this.rechargeTip = this.cardDetail.rechargeTip; // 付款金額提示充值
}).catch( err => {
console.log(err)
})
}
}
3、接口返回:
promise.all中console.log(res) 返回的是數(shù)組接口返回

4、注意:
Promise.all 缺陷 如果其中某個任務(wù)出現(xiàn)異常(reject),所有任務(wù)都會掛掉,Promise直接進入 reject 狀態(tài)至catch回調(diào)。
Promise.allSettled 無論一個任務(wù)正?;蛘弋惓?,都會返回對應(yīng)的的狀態(tài),可以解決上述問題
補充知識:vue項目中Promise同步請求
1.js中定義Promise
export function wxLogin() {
let pResult = new Promise((resolve, reject) => {
uni.login({
provider: 'weixin',
success: (res) => {
console.log('login success:', res);
// return res;
setTimeout(function() {
resolve(res);
}, 3000);
},
fail: (err) => {
console.log('login fail:', err);
reject(err);
}
});
}).catch(res => {
console.log(666, res);
})
return pResult;
}
2.vue文件中使用
import {login,wxLogin} from '@/common/login.js'
(async () => {
//獲取授權(quán)狀態(tài)
console.log(1111,"111")
let aaa = await wxLogin();
console.log(3333,"3333");
console.log(4444,aaa);
})()
以上這篇在vue項目中promise解決回調(diào)地獄和并發(fā)請求的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue ElementUI this.$confirm async await封
這篇文章主要介紹了Vue ElementUI this.$confirm async await封裝方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09

