axios解决高并发的方法:axios.all()与axios.spread()的操作
前言:
很多时候,我们可能需要同时调用多个后台接口,就会高并发的问题,一般解决这个问题方法:
axios.all和axios.spread
***注意这里的$get是封装的axios方法 //方法一: searchTopic(){ returnthis.$axios({ url:'地址1', method:'方式',//get/post/patch/put/deleted params:{//参数get所以用params。post.put用data } }) } //方法二: searchs(){ returnthis.$axios({ url:'地址1', method:'方式',//get/post/patch/put/deleted params:{//参数get所以用params。post.put用data } }) }, axios.all([searchTopic(),searchs()]) .then(axios.spread(function(allSearchTopic,allSearchs){ debugger//打印可以拿到所有的返回值 allSearchTopic==方法一的返回值 allSearchs==方法二的返回值 }));
补充知识:axios.all及Promise.all合并多个请求且都返回数据后进行其他操作
很多时候,我们需要同时向后端进行多个请求,当所有请求都返回数据后,再进行一些操作。
比如:初始化页面时,可能需要初始化一些基础数据,才能进行操作。
获取这些基础数据,可能需要向后端发送request1,request2。。。
等多个请求,而后续的操作说需要request1,request2等都正确返回数据后才能进行。
在axios官方文档中对一次性并发多个请求示例如下:
functiongetUserAccount(){ returnaxios.get('/user/12345'); } functiongetUserPermissions(){ returnaxios.get('/user/12345/permissions'); } axios.all([getUserAccount(),getUserPermissions()]) .then(axios.spread(function(acct,perms){ //当这两个请求都完成的时候会触发这个函数,两个参数分别代表返回的结果 }))
但是很多时候,我们在项目中并不会直接去axios.get,axios请求可能都放在一个文件中,并且对加了拦截器等等。示例如下:
exportconstcargoDayNumber=(data)=>{ returnaxios.request({ url:'/api/zz-xt/statistical/areas', method:'post', data:data }) }
在vue文件中的使用如下:
letr1=carVisitTime({createTime:'2019-06-27'}) letr2=statistic({createTime:'2019-06-27'}) letr3=cargoDayNumber({createTime:'2019-07-01'}) letr4=enterpriseRanking() axios.all([r1,r2,r3,r4]).then( axios.spread((r1,r2,r3,r4)=>{ this.numberVehicleVisits=r1.data this.loadingDateRank.loading=r2.data.loading this.loadingDateRank.unloading=r2.data.unloading this.loadingAreasRank.loadingRegionalList=r3.data.inflow this.loadingAreasRank.unloadingRegionalList=r3.data.outflow this.enterpriseLoadWeight.enterpriseLoadingRankList=r4.data.loadingRank this.enterpriseLoadWeight.enterpriseUnloadingRankList=r4.data.unloadingRank }) )
除了axios.all,我们也可以使用Promise.all,示例如下
Promise.all([p1,p2]).then(function(values){ console.log(values);//values为一个数组 ///进行你的下一步操作 });
以上这篇axios解决高并发的方法:axios.all()与axios.spread()的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。