遇到的一个问题是一个方法调多个异步的问题,由于本人很菜所以没有解决这个问题,后面也有开群友们帮忙看了说用async
,await
来解决起先我加了给你们上代码看看 错误的问题:
print() {
this.list.forEach(async(item) => {
const res = await this.Promise1(item);
item["cc"] = res.cc
console.log("执行处理数据")
})
this.Promise2(JSON.parse(JSON.stringify(this.list))).then((res) => {
console.log("数据后所执行的",res)
})
},
解决的方法:
- 使用promise的链式调用的方式在循环内部走判断 这个有点消耗性能
- 使用for循环替换forEach 修改成同步执行 小编这里只上一个for的其他为啥子不写因为太懒了
- 这个其实跟链式调用没什么区别 使用promise.all的方法把循环里面的promise都记录下来
async print() { for(let i=0; i<this.list.length; i++) { const item=this.list[i]; const res=await this.Promise1(item); item['cc']=res.cc; console.log("+++forEach的异步") } this.Promise2(JSON.parse(JSON.stringify(this.list))).then((res) => { console.log("数据后所执行的",res); }) },