axios解决高并发的方法:axios.all()与axios.spread()的操作 以便本人查阅
1.前言
在官方 axios 中,还提供了 axios.all和axios.spread 这两个方法,这两个方法主要是为了执行多个并发请求,官方文档中,它们的用法示例如下:
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread((getUserAccount, getUserPermissions) => {
// 两个请求都完成后,操作
}));
从用法示例中可以看出:
axios.all方法接受一个数组作为参数,数组中的每个元素都是一个请求,返回一个[promise]对象,当数组中所有请求均已完成时,执行then方法。
在then方法中执行了 axios.spread 方法。该方法是接收一个函数作为参数,返回一个新的函数。接收的参数函数的参数是axios.all方法中每个请求返回的响应。
axios.all及Promise.all合并多个请求且都返回数据后进行其他操作
vue 实力
created() {
const loading = this.$loading({
lock: true,
text: 'Loading',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
axios.all([this.get_banner(), this.get_activity(), this.get_brand(), this.axios_getList(), this.axios_post_getList()])
.then(axios.spread((banner, activity, get_brand, getList, axios_post_getList, axios_popUps,) => {
if (banner.code === 200) {
this.my_swiper = banner.data;
}
if (activity.code === 200) {
this.slide_PerView = activity.data;
}
if (get_brand.code === 200) {
this.activityList = get_brand.data;
}
if (getList.code === 200) {
this.promote = getList.data;
}
if (!sessionStorage.getItem('spread')) {
this.axios_popUps().then((axios_popUps) => {
if (axios_popUps.code === 200) {
this.spread.list = axios_popUps.data;
sessionStorage.setItem('spread', true)
}
})
}
if (axios_post_getList.code === 200) { // code == 200时
this.footlist = axios_post_getList.data; // 初始化赋值
}
this.$nextTick(() => {
this.get_homepagespu(this.pageNum)
.then((homepagespu) => {
if (homepagespu.code === 200) {
this.homepagespu = homepagespu.data.data;
this.total = homepagespu.data.data.length;
this.loading = false;
}
})
});
loading.close();
}));
},