项目中我们经常遇到一个功能界面需要请求多个接口的数据才能做渲染。如果顺序不对还会出现界面报错。ES6的Promise.all可以解决这个问题。同时请求多个服务,并且将结果以数组形势返回。
// 初始化数据
initData(code) {
this.loading = true
let p1 = new Promise((resolve, reject) => {
favourableApi
.timeQuery({ favourableCode: code })
.then(res => {
resolve(res)
})
})
let p2 = new Promise((resolve, reject) => {
favourableApi
.query({
favourableCode: code
}).then(data => {
resolve(data)
})
})
Promise.all([p1, p2]).then(arry => {
let favourableTimesData = arry[0]
let favourableFormData = arry[1][0]
// 处理优惠有效期数据
Reflect.set(favourableTimesData, 'weeks', favourableTimesData.weeks.split(','))
Reflect.set(favourableFormData, 'favourableTimes', favourableTimesData)
// 处理优惠基本信息和规则信息
Reflect.set(favourableFormData, 'conditionRule', JSON.parse(
favourableFormData.conditionRule
))
Reflect.set(favourableFormData, 'actionRule', JSON.parse(
favourableFormData.actionRule
))
this.favourableForm = Object.assign({}, favourableFormData)
this.loading = false
})
},
网友评论