最近在一个项目中需要获取用户的列表,并根据每个用户的id查找对应的角色的功能。主要过程是:首先获取用户列表,在then中,使用Promise.all方法将遍历接口功能作为参数输入。具体代码如下:
getRoleName(item,index){
return new Promise((resolve, reject)=>{
getRoles({userid: item.id}).then(res=>{
resolve({id:item.id,role:resdata})
})
})
},
getUserList(params).then((res) => {
const {code,data} = res.data;
if(code>0) {
const {list,total}=data
_this.dataSource = list
_this.total = total
// // 处理角色
let promiseArray=_this.dataSource.map((item,index)=>{
return _this.getRoleName(item,index)
})
Promise.all(promiseArray).then(roles=>{
for(let i=0;i<roles.length;i++){
if(_this.dataSource[i].id==roles[i].id){
_this.dataSource[i].role=roles[i].role
}
}
})
}
})