網(wǎng)站的反鏈要怎么做百度首頁(yè)推薦關(guān)不掉嗎
一、背景
在開(kāi)發(fā)中遇到在循環(huán)中調(diào)用異步接口的問(wèn)題,導(dǎo)致頁(yè)面渲染完成時(shí),沒(méi)有展示接口返回后拼接的數(shù)組數(shù)據(jù)。
二、問(wèn)題
在代碼中使用了map進(jìn)行循環(huán),導(dǎo)致調(diào)用接口的時(shí)候處于異步。
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); // 異步請(qǐng)求let obj ={url: res,pathUrl: it};await el.fileList.push(obj);})}this.items.push(el);})
三、解決方案
經(jīng)過(guò)斷電調(diào)試時(shí),發(fā)現(xiàn)數(shù)組里面的最后一個(gè)數(shù)據(jù)是遍歷第一個(gè)數(shù)據(jù)接口返回的內(nèi)容,然后搜索map是否支持異步變同步,發(fā)現(xiàn)map是不支持的。通過(guò) for..of 去遍歷數(shù)組,通過(guò)async await 把異步變同步,解決不顯示內(nèi)容的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);}
四、參考鏈接
不同循環(huán)方式是否支持異步變同步可以參考一下鏈接:
https://blog.csdn.net/weixin_42756432/article/details/103880033