问题
循环遍历一个数组,每个数据项都需要调用接口请求数据(异步),如果用forEach 和 map 等数组方法去遍历,异步的函数是不会等待的,加了await也没有作用(下面的循环了5次)
methods: {
async getList2() {
//异步请求数据
await getStaff(this.queryParams).then((response) => {
console.log("222222----");
});
},
async printAllPDF() {
staffList.forEach(async (item) => {
console.log("111111----");
//调用异步的函数
await this.getList2();
});
console.log("333333----");
},
},
我希望得到的应该是 输出一个“111111----”,再输出一个“222222----”,循环5次后最后输出“333333----”,但是实际的情况如下:
输出了5次“111111----”,又输出了“333333----”。因为执行异步函数this.getList2();并没有等它执行完,5个异步后面执行,所以出错,使用的数据也会出现错乱
因为数组的方法(forEach, map, filter 等)通常是同步执行的,而且,就算我使用Promise.all 来等待每一个异步执行完再执行后面的语句
methods: {
async getList2() {
//异步请求数据
await getStaff(this.queryParams).then((response) => {
console.log("222222----");
});
},
async printAllPDF() {
let promises = []
staffList.forEach(async (item) => {
console.log("111111----");
//调用异步的函数
const ceshiItem = await this.getList2();
promises.push(ceshiItem)
});
await Promise.all(promises)
console.log("333333----");
},
},
也是无济于事,输出还是一样的结果
解决方法
使用for of 遍历
methods: {
async getList2() {
//异步请求数据
await getStaff(this.queryParams).then((response) => {
console.log("222222----");
});
},
async printAllPDF() {
for(const item of staffList){
console.log("111111----");
//调用异步的函数
await this.getList2();
}
console.log("333333----");
},
},
正确输出: