2022/1/18 同步异步for和forEach
遇到的一个问题是一个方法调多个异步的问题,由于本人很菜所以没有解决这个问题,后面也有开群友们帮忙看了说用async,await来解决起先我加了给你们上代码看看 错误的问题:
data() {
return {
list: [{
index: 1
}, {
index: 1
}, {
index: 1
}, {
index: 1
}],
}
},
created() {
this.print()
},
methods: {
print() {
this.list.forEach((item) => {
this.Promise1(item).then(res => {
item["cc"] = res.cc
console.log("执行处理数据")
})
})
this.Promise2(JSON.parse(JSON.stringify(this.list))).then((res) => {
console.log("数据后所执行的",res)
})
},
Promise1() {
return new Promise(function(resolve, reject) {
let arr = {
cc: '测试'
};
模拟接口返回
setTimeout(() => {
resolve(arr);
}, 1000)
})
},
Promise2(list) {
return new Promise(function(resolve) {
resolve(list);
})
}
}
}
到这一步很多人都会说你写错了少了async,await我们先看一下输出吧!
然后我们加上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的链式调用的方式在循环内部走判断 这个有点消耗性能
- 这个其实跟链式调用没什么区别 使用promise.all的方法把循环里面的promise都记录下来
- 使用for循环替换forEach 修改成同步执行 小编这里只上一个for的其他为啥子不写因为太懒了
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);
})
},
为什么使用for可以解决这个问题呢? 起初我也是比较疑惑的后面群友让我去看了一下手写forEach
Array.prototype.myforEach = function (callback) {
let index = -1;
const length = this.length;
while (++index < length) {
callback(this[index], index);
}
return this;
};
async await 因为while循环阻止async io任务这个小编解释不出来 你们可以自己去搜索一下看看别人的文章 应该说得比较清楚!(然后各位大佬们觉得有我写错了的可以提出来,我这边虚心接受,因为本人太菜了嘿嘿)