vue async 同步调用 多层异步嵌套

DAY DAY UP 2021年04月21日 268次浏览

vue 钩子函数 create 前加 async

async created(){
            //测试调用多层异步等待方法
            if( await this.testAwait() == 123){
              console.log("456");
            };
            this.getDetail();
            this.getTenancyData();
        },

定时器模拟 10s 后加载

methods:{
            async testAwait(){
               let result = await this.testAwait10s()
               console.log("testAwait",result);
               return result
            },
          async testAwait10s(){
               return new Promise((resolve, reject) =>
                 {
                   console.log("testAwait")
                   //模拟耗时操作
                   setTimeout(function(){
                     console.log("await over")
                     resolve(123)
                   },10000);
                   //放回数据通过 resovlve 返回
                   resolve(123);
                 }
               )               
            },
}

模拟正常调用 异步延时

methods:{
            async testAwait(){
               let result = await this.testAwait10s()
               console.log("testAwait",result);
               return result
            },
          async testAwait10s(){
               await this.getDetail();
               return(123);
            },
	async getDetail(){
                let that = this;
                await this.axios.post("/aggregateAffairService/getAggregateDetail",{query: {id: this.$route.params.id}}).then(res=>{
                    this.id = this.$route.params.id;
                    this.expire_seconds=res.data.data.affair_service_def.expire_seconds;
        })
}