vue for 循環(huán)中使用 await(轉(zhuǎn))
await 和 async必須成對出現(xiàn),如果調(diào)用await的地方眼坏,無法正確匹配到async則會報錯,例如:forEach外面寫async宰译,forEach中使用await,則無法匹配沿侈。
async? tidyData(){
item.categorys.forEach(asyncitem2 => {
let customModelList =await? this.tidyDataCustom(item2)
? ? })
}
forEach:
async tidyData(){
await Promise.all(
item.categorys.forEach(asyncitem2 => {
letcustomModelList =await this.tidyDataCustom(item2)
? ? ? ? })
? ? )
}
for:
async tidyData(){
for(let item2 of item.categorys){
// 款式選項數(shù)據(jù)整理
let customModelList =await? this.tidyDataCustom(item2)
? ? }
}
forEach屬于并發(fā)操作,所以需要鎖定住每一個循環(huán)體咳短,而for不是并發(fā)操作,所以無需鎖定每一次的循環(huán)咙好。
如果需要等待的方法中也去async并且等待里面的耗時操作,可以如下方式:
tidyDataCustom(item2){
return newPromise(async resolve => {
await this.getCategoryStyle(item2)
? ? ? ? resolve()
? ? })
}
返回結(jié)果放入到resolve(xx)中勾效,如果沒有結(jié)果就resolve()