美文网首页
多个请求并发,解决数据不固定的问题

多个请求并发,解决数据不固定的问题

作者: 焚心123 | 来源:发表于2020-08-14 16:42 被阅读0次
  • 当我们使用同一个接口,七天的不同时间 来获取数据

  • 思路:1.我们用封装一个方法,里面用promise请求,将我们请求成功的数据返回

//在methods中
  qiX(url,data){//前7天数据新增
            return new Promise(reslove=>{
                this.$axios.get(`https://elm.cangdu.org/statis/${url}/${data}/count`).then(res=>{
                    if(res.data.status==1){
                        reslove(res.data.count);
                    }
                })
            })
        },
  • 2.在mounted生命周期中调用方法,并循环时间的数组和传参

   created(){
            const dateList = [...Array(7).keys()].map(days => {
            let t = new Date(Date.now() - 86400000 * days);
            let m=t.getMonth() + 1;
            let a=m<10?'0'+m:m;
            let str = `${t.getFullYear()}-${a}-${t.getDate()}`;
            // console.log('aa', srt);
            return str;
        });
            console.log(dateList);
            this.y=dateList.reverse();
            // this.y=dateList;//七天时间的整个数组
            this.timer();
    },
    async mounted(){
        this.$axios.all([this.axOne(),this.axTwo(),this.axThree(),this.axFour(),this.axFive(),
        this.axSix()])
        .then(this.$axios.spread((res1, res2,res3,res4,res5,res6)=>{
            // console.log(res1.data.count);
            this.one=res1.data.count;
            this.two=res2.data.count;
            this.three=res3.data.count;
            this.four=res4.data.count;
            this.five=res5.data.count;
            this.six=res6.data.count;
            // console.log(res2);
            // console.log(res3);
        }));

        //
        var p=[];
        var p1=[];
        var p2=[];
        for(var i=0;i<this.y.length;i++){
            var a=this.qiX('user',this.y[i]);//user接口的 七天时间
            p.push(a);
            var b=this.qiX('order',this.y[i]);//user接口的 七天时间
            p1.push(b);
             var c=this.qiX('admin',this.y[i]);//user接口的 七天时间
            p2.push(c);
        }
        Promise.all(p).then(res=>{
            console.log(res);
            this.xX=res;
        });
        Promise.all(p1).then(res=>{
            console.log(res);
            this.xD=res;
        });
        Promise.all(p2).then(res=>{
            console.log(res);
            this.xG=res;
        })
    },
  • 3.在通过promise.all多并发请求将我们请求的数据按照顺序返回,否则返回的数据会根据网络请求的快慢而变化,这样会导致我么获取的数据不是固定的

  • 当然我们也可以在循环时间里面,直接通过async , await 来获取数据,这样将我们请求的异步的数据转换为同步的,从而得到的数据也是固定的,不会随着页面的刷新,位置是随机的

相关文章

网友评论

      本文标题:多个请求并发,解决数据不固定的问题

      本文链接:https://www.haomeiwen.com/subject/gistghtx.html