新聞中心
這篇文章將為大家詳細(xì)講解有關(guān)vue項(xiàng)目中利用promise解決并發(fā)請(qǐng)求的方法,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
場(chǎng)景需求:
需要同時(shí)請(qǐng)求5個(gè)接口
都請(qǐng)求成功后執(zhí)行下一步操作
解決方法:
定義一個(gè)變量i=5,請(qǐng)求成功一個(gè)接口,讓i–,直到i=0時(shí)執(zhí)行下一個(gè)操作,否則不執(zhí)行
axios.all 并發(fā)請(qǐng)求,.then(axios.spread(function(callback1, callback2)){})
promise.all 并發(fā)請(qǐng)求,.then(function([callback1, callback2]){})
1、回調(diào)地獄:
函數(shù)作為參數(shù)層層嵌套
代替的為.then的鏈?zhǔn)讲僮?/p>
2、promise.all并發(fā)請(qǐng)求
引入接口
import {getSellerDetail} from '../../api/seller'
import {getMemberCardInfo} from '../../api/pay_online/index'
數(shù)據(jù)處理
1. 創(chuàng)建一個(gè)Promise實(shí)例,獲取數(shù)據(jù)
2. 并把數(shù)據(jù)傳遞給處理函數(shù)resolve和reject
3. promise在聲明時(shí)就執(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) }) }) `// 會(huì)員卡信息` 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對(duì)象都完成執(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; // 會(huì)員卡信息 this.cardDetail = res[1].data; this.balance = this.cardDetail.balance; //余額 this.rechargeTip = this.cardDetail.rechargeTip; // 付款金額提示充值 }).catch( err => { console.log(err) }) } }
文章題目:vue項(xiàng)目中利用promise解決并發(fā)請(qǐng)求的方法-創(chuàng)新互聯(lián)
鏈接地址:http://www.ef60e0e.cn/article/djcoej.html