前提条件,遍历数组,调用接口进行赋值,数据加载完成前会有loading遮罩
数组如下:
const userList= [
{id:'123',name:'chen',gender:'female'},
{id:'124',name:'zhang',gender:'male'},
{id:'125',name:'xia',gender:'female'}
]
model(UserInfo)如下:
export class UserInfo {
id:string;
name:string;
gender:string;
phone:string;
}
调用接口如下:
async setUserInfo(id, userInfo:UserInfo) {
const result = await this.service.getUsrInfoById(id);
const data = result.data;
if (data) {
userInfo.phone = '1234567';
}
return userInfo;
}
1、forEach
this.loading = true; // 遮罩开始
if (userList && userList.length > 0) {
userList.forEach(async (element:any) => {
const result = await this.setUserInfo(element.id, element);
if (result) {
element.phone = result.phone;
}
});
}
this.loading = false; // 遮罩结束
return userList;
结果:遮罩效果不明显且数据加载速度较慢
原因分析:1、forEach是异步的,会先执行this.loading = false;
从而导致遮罩无法实现效果;2、for循环请求接口,每次都需要前一个请求完成才会进行下一个接口请求,因此加载速度慢
2、for of
this.loading = true; // 遮罩开始
if (userList && userList.length > 0) {
for (const element of userList) {
const result = await this.setUserInfo(element.id, element);
if (result) {
element.phone = result.phone;
}
}
}
this.loading = false; // 遮罩结束
return userList;
结果:遮罩效果正常,但是数据加载速度较慢
原因分析:1、for of是非异步,因此遮罩效果正常,2、for循环请求接口,每次都需要前一个请求完成才会进行下一个接口请求,因此加载速度慢
3、for of + Promise.all
this.loading = true; // 遮罩开始
const promise:Array<Promise<any>> = [];
if (userList && userList.length > 0) {
for (const element of userList) {
promise.push(this.setUserInfo(element.id, element));
}
}
const result = await Promise.all(promise);
userList.forEach((element:UserInfo, index: number) => {
element.phone = result[index].phone;
});
this.loading = false; // 遮罩结束
return userList;