How do I wait until all requisitions have ended?

3

How can I execute the sortOrder function as soon as the getOrders function finishes all requests?

I thought about using a callback , but without success, any suggestions of a promise or code that uses callback?

Currently my code looks like this:

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
    }
}
    
asked by anonymous 29.11.2018 / 14:53

1 answer

4

The "Vue-like" solution, ie using the reactivity that Vue offers, is to sortOrder a computed property which depends on this.orderInfo . This causes the sortOrder code to be run whenever this.orderInfo changes. Attention that .sort() changes the original array, this can give unwanted effects in particular in a reactive environment such as Vue ...

Actually, thinking this way, I would give new names and do the thing like this:

module.exports = {
  data() {
    return {
      orders: [],
      orderInfo: [],
    }
  },
  mounted() {
    this.user = this.$q.localStorage.get.item('userInfo')
    axios.get('${api.getOrders}${this.user.cpf}').then(response => {
      this.orders = response.data;
    })
  },
  computed: {
    sortedOrder() {
      return this.orderInfo.slice().sort(this.compare);
    }
  },
  watch: {
    orders() {
      if (this.orders.length > 0) {
        this.$q.loading.show();
        this.getOrders();
      }
    },
    sortedOrder() {
      this.$q.loading.hide();
    }
  },
  methods: {
    getOrders: function() {
      const orders = this.orders.map(order => {
        const endpoint = api.obterOrderInfo(order.orderId);
        return axios.get(endpoint).then(response => response.data)
      });
      Promise.all(orders).then(orderInfo => this.orderInfo = orderInfo);
    },
    compare: function(x, y) {
      return x.creationDate < y.creationDate
    }
  }
};
    
29.11.2018 / 15:11