欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > 循环实现异步变同步的问题

循环实现异步变同步的问题

2024/10/23 23:25:35 来源:https://blog.csdn.net/qq_42312329/article/details/140933139  浏览:    关键词:循环实现异步变同步的问题

一、背景

在开发中遇到在循环中调用异步接口的问题,导致页面渲染完成时,没有展示接口返回后拼接的数组数据。

二、问题

在代码中使用了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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com