美文网首页
Vue--- 中 async与await的使用

Vue--- 中 async与await的使用

作者: 输入昵称就行 | 来源:发表于2019-05-11 23:55 被阅读0次

很多时候我没有很多业务,需要依次调用多个后台接口,并且后一个接口需要依赖前一个接口的响应结果,如果上一个接口挂了,后一个接口也就不需要调用了。

举例说明

手机话费充值,给定一个输入框,当用户输入完号码,输到11位的时候,自动调用获取号码所属地,然后根据所属地列出所有的可充值的面额。

普通写法

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);
      }
    }
}

相关文章

网友评论

      本文标题:Vue--- 中 async与await的使用

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