前言
最近在开发的项目中 因为要循环处理后端接口返回的数据时,使用map方法,但是在循环体中使用async await 想拿到返回的数据,然后发现渲染页面的时候,数据会部分消失,导致位置错乱,当时以为是v-for渲染diff算法有问题,更改了key值为id没有解决,几经波折
最后发现是因为map内部使用了while和callback方式来执行函数,await不会等待callback的执行。forEach同理。 因为是公司内网 所有代码就不方便透露了。解决方法有两种
- 使用for循环
const data = async () => {
const arr = [1,2,3,4,5];
for (let i = 0; i < arr.length; i++) {
await this.getInfo().then();//你的请求方法
}
}
2.使用promise.all()
const data = async () => {
const arr = await Promise.all(
arr.map(async (v) => {
await API.GETRADARPNG().then();//你的请求方法
})
);
return arr;
};