将每个请求封装成promise对象,当请求到数据后都resolve出去,再调用Promsie.all方法将每个promise对象作为参数传入进去。这样每个api的promise对象状态都resolve“解决后”,就能在 Promise.all([p1,p2…p]).then中拿到所有api请求完成的状态,从而实现效果。
created() {
this.loading = true
Promise.all([
this.getAccountList(),
this.getCustomerList()
]).finally((arr) => {
this.loading = false
})
},
methods: {
getAccountList() {
return new Promise((resolve) => { // 关键代码
getAccountList().then((res) => { // 接口
this.accountOptions = res.data.map(item => {
const obj = {
code: item.code,
name: item.name,
}
return obj
})
resolve(this.accountOptions) // 关键代码
})
})
},
getCustomerList() {
return new Promise((resolve) => {
getCustomerList().then((res) => {
this.customerOptions = res.data.map(item => {
const obj = {
code: item.code,
name: item.name,
}
return obj
})
resolve(this.customerOptions)
})
})
},
}
标签:code,return,resolve,res,JS,item,loading,Promise
From: https://blog.csdn.net/qq_44170108/article/details/136643496