javascript - 我如何等到所有请求都完成?
问题描述
功能完全完成后,如何使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
}
}
解决方案
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))
},
推荐阅读
- google-sheets - 在 Google 表格中定义命名范围时可以跳过范围吗?
- python - 使用 tkinter 中的按钮启动/停止 while 循环
- python - 如何使用 CASCADE 指令以 ORM 方式使用 SqlAlchemy 清除 PostgresDB
- java - 没有 Spring Security 的 Spring Boot Web API 上的错误 403
- javascript - 如何使用先前从 JSON 获取并解析为对象的 td{element) 数据将行附加到表中
- angular - 如果不是 mat-button-toggle-group 的直接子代,则 Mat-button-toggle 会丢失组样式
- swift - 在 Swift 中使用 UICollectionCell 获取属性不会覆盖其超类中的任何属性
- thrift - Thrift 二进制协议错误
- django - 使用 html 表单在 django 中呈现页面
- python - 尝试编写代码但收到错误:IndexError: string index out of range