vue中使用async和await

114 阅读1分钟

普通写法

methods: {
    // 获取所属地
    getLocation(phoneNum) {
        return axois.post('/location', {phoneNum});
    },
    // 根据属地获取充值面额列表
    getFaceList(province, city) {
        return axois.post('/location', {province, city});
    },
    // 采取链式的调用方法
    getFaceResult() {
      this.getLocation(this.phoneNum)
          .then(res => {
              if (res.status === 200 && res.data.success) {
                  let province = res.data.province;
                  let city = res.data.city;
                  this.getFaceList(province, city)
                      .then(res => {
                          if(res.status === 200 && res.data.success) {
                              this.faceList = res.data
                          }
                      })
              }
          })
          .catch(err => {
              console.log(err)
          })  
    }
}

async await写法

methods: {
    // 获取所属地
    getLocation(phoneNum) {
        return axois.post('/location', {phoneNum});
    },
    // 根据属地获取充值面额列表
    getFaceList(province, city) {
        return axois.post('/location', {province, city});
    },
    // 采取async await 方式调用
    async getFaceResult() {
      // 异常需要通过try catch补货  
      try {
          let location = await this.getLocation(this.phoneNum);
          // 程序会等待上一个请求完成才进行下一条的语句执行
          
          if (location.data.success) {
              let province = location.data.province;
              let city = location.data.city;
              let result = await this.getFaceList(province, city);
              if (result.data.success) {
                  this.faceList = result.data;
              }
          }
      } catch(err) {
          console.log(err);
      }
    }
}

练习

<template>
    <div>
    </div>
</template>

<script>
    export default {
        mounted() {
            this.allFun()
        },
        methods: {
            async allFun() {
                try {
                    let one = await this.oneFun()
                    console.log(one)
                    if (one == '') {
                        let two = await this.twoFun()
                        console.log(two)
                    } else {
                        setTimeout(() => {
                            console.log('有值')
                        }, 5000)
                    }
                } catch (e) {
                    //TODO handle the exception
                }

            },
            oneFun() {
                let num = new Promise(resolve => {
                    setTimeout(() => {
                        resolve('1111111')
                    }, 2000)
                })
                return num
            },
            twoFun() {
                let twonum = new Promise(resolve => {
                    setTimeout(() => {
                        resolve('2222')
                    }, 3000)
                })
                return twonum
            }

        },
    }
</script>

<style scoped>

</style>