3
How could I perform the function sortOrder as soon as the function getOrders complete all requests?
The idea is to sort all orders by latest purchase date.
Code
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
}
}
You should call the function
getOrdersin the Mounted?– Marconi
@Marconi sorry I was on the train and I got no reception. Yes the
this.getOrders()has to be called, but within thewatch. So he is called whenever theorderschange. It may take a debauchery, but I think it serves your case.– Sergio
Along those lines
Promise.all(orders)...Orders is Undefined, something I should add to the @Sergio code?– Marconi
@Marconi forgot a
returnbeforeaxios.get. I corrected you now.– Sergio
Now yes hehehe, thank you very much @Sergio, great learning here :)
– Marconi
The only question I was left with was here
Promise.all(orders).then(orderInfo => this.orderInfo = orderInfo);. I understood that you add all the requests in an array and as soon as they respond you add them inorderInfo, that would be the logic?– Marconi
@Exact Marconi! The
Promise.alltransforms an asynchronous array into a synchronous array. What is given to you in.then(orderInfois the array in the same order as the files insideorders. When thePromise.allhas run all these events gives the result of thesethen. You should also have a.catch()to catch the mistakes, but I think you know that.– Sergio