Reputation: 1184
How could I make the sortOrder
function run once the getOrders
function is fully completed?
I thought using a callback, so I expect getOrders to terminate and execute the sortOrder function, but I don´t know how to do that. What should I do, any sugestions?
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
}
}
Upvotes: 2
Views: 2529
Reputation: 2071
You'll need to wrap your promises together and solve them with a Promise.all
like this:
getOrders: function () {
let promises = []
for (let i = 0; i < this.orders.length; i++) {
const promise = axios.get(api.obterOrderInfo(this.orders[i].orderId)).then(response => {
this.orderInfo = this.orderInfo.concat(response.data)
})
promises.push(promise)
}
Promise.all(promises)
.then(() => {
this.sortOrder()
})
},
Upvotes: -1
Reputation: 218
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))
},
Upvotes: 3