等待直到API完全加载,然后运行下一个功能(异步/等待),此功能将作用



我是JavaScript的初学者,对VUEJS的了解有所了解。我有一个名为tickets的数组。我也有一个数据API返回两个不同的数据对象(门票和用户配置文件(。

门票具有用户ID,用户配置文件具有带有名称的ID。

我需要创建一种查看这两个数据的方法,循环循环,并将用户的全名分配给视图。

我有一个问题,我的门票对象未完成加载,有时会导致诸如firstname is undefined之类的错误。因此,我以为我会尝试编写一种异步/等待的方法,等待门票满载。

尽管我的代码有效,但它只是"感觉正确",我不确定一旦应用程序变大,它将有多可靠。

我可以另一集的目光以确认我当前的方法还可以吗?谢谢!

data() {
    return {
      isBusy: true,
      tickets: [],
      userProfiles: [],
    }
  },
  created() {
    this.getUserProfiles()
    this.getTickets()
  },
  methods: {
    getUserProfiles: function() {
      ApiService.getUserProfiles().then(response => {
        this.userProfiles = response.data
      })
    },
    getTickets() {
      ApiService.getTickets().then(response => {
        this.tickets = response.data
        this.assignNames(this.tickets)
        this.isBusy = false
      })
    },
    // lets wait until the issues are loaded before showing names;
    async assignNames() {
      let tickets = await this.tickets
      var i
      for (i = 0; i < this.tickets.length; i++) {
        if (tickets[i].assigned_to !== null) {
          const result = this.userProfiles.filter(profile => {
            return profile.uid == tickets[i].assigned_to
          })
          tickets[i].assigned_to = result[0].firstname + ' ' + result[0].lastname
        }
      }
    }
  }
}
</script>

有几种方法可以做到这一点。这是我不喜欢async/await的那个:

created() {
  this.load();
},
methods: {
  getUserProfiles: function() {
    return ApiService.getUserProfiles().then(response => {
      this.userProfiles = response.data
    })
  },
  getTickets() {
    return ApiService.getTickets().then(response => {
      this.tickets = response.data
    })
  },
  load() {
    Promise.all([
      this.getUserProfiles(),
      this.getTickets()
    ]).then(data => {
      this.assignNames();
      this.isBusy = false;
    });
  },
  assignNames(){
    const tickets = this.tickets;
    for (let i = 0; i < this.tickets.length; i++) {
      if (tickets[i].assigned_to !== null) {
        const result = this.userProfiles.filter(profile => {
          return profile.uid == tickets[i].assigned_to
        })
        tickets[i].assigned_to = result[0].firstname + ' ' + result[0].lastname
      }
    }
  }
}

最新更新