一、背景
在开发中遇到在循环中调用异步接口的问题,导致页面渲染完成时,没有展示接口返回后拼接的数组数据。
二、问题
在代码中使用了map进行循环,导致调用接口的时候处于异步。
this.form.list.map(async el=>{el.fileList = [];if(el.picture !== ""){const arr = el.picture.split(',');console.log(arr,"arr")arr.map(async it => {let res = await this.transferImage(it); // 异步请求let obj ={url: res,pathUrl: it};await el.fileList.push(obj);})}this.items.push(el);})
三、解决方案
经过断电调试时,发现数组里面的最后一个数据是遍历第一个数据接口返回的内容,然后搜索map是否支持异步变同步,发现map是不支持的。通过 for..of 去遍历数组,通过async await 把异步变同步,解决不显示内容的bug
// 方法上有 async
for await (let el of this.form.list) {el.fileList = [];if(el.picture !== ""){const arr = el.picture.split(',');console.log(arr,"arr")for await (const it of arr) {let res = await this.transferImage(it);let obj ={url: res,pathUrl: it};await el.fileList.push(obj);}}this.items.push(el);}
四、参考链接
不同循环方式是否支持异步变同步可以参考一下链接:
https://blog.csdn.net/weixin_42756432/article/details/103880033