首页 > 解决方案 > 我如何等到所有请求都完成?

问题描述

功能完全完成后,如何使sortOrder功能运行?getOrders

我想使用回调,所以我希望 getOrders 终止并执行 sortOrder 函数,但我不知道该怎么做。我该怎么办,有什么建议吗?

mounted () {
    this.user = this.$q.localStorage.get.item('userInfo')
    axios.get(`${api.getOrders}${this.user.cpf}`).then(response => {
      this.orders = response.data
      if (this.orders !== '') {
        this.$q.loading.show()
        this.getOrders(callback => {
          this.sortOrder()
        })
      }
    })
  },
  methods: {
    getOrders: function () {
      for (let i = 0; i < this.orders.length; i++) {
        axios.get(api.obterOrderInfo(this.orders[i].orderId)).then(response => {
          this.orderInfo = this.orderInfo.concat(response.data)
        })
      }
    },
    sortOrder: function () {
      this.orderInfo.sort(this.compare)
      this.$q.loading.hide()
    },
    compare: function (x, y) {
      return x.creationDate < y.creationDate
    }
}

标签: javascriptvue.js

解决方案


getOrders: function () {
   // Create array of requests
   const requests = [];
   for (let i = 0; i < this.orders.length; i++) {
      requests.push(axios.get(api.obterOrderInfo(this.orders[i].orderId)))
   }

   // Map array of responses to orderInfo
   return Promise.all(requests).then(results => this.orderInfo = results.map(result => result.data))
},

推荐阅读