reqData(){
this.startLoading();
//获取分析结果数据
for (let i = 1; i <=24;i += 1) {
try {
let formattedValue = i.toString().padStart(4, '0');
this.requestData(formattedValue).then((PromiseResult) => {
if(PromiseResult.status==="success"){
this.images.push(PromiseResult.image)
this.positions.push(PromiseResult.position)
}
}).catch((error) => {
// 处理错误
console.error(error);
});
} catch (error) {
console.error(`Error fetching data for value ${formattedValue}:`, error);
}
}
console.log("数据请求成功");
this.endLoading();
},
需求:要等for循环中的异步任务所有完成才向下运行
使用 async/await 来等待所有异步任务完成后再执行后续代码
怎样使用嘞?配合Promise
async reqData() {
this.startLoading();
try {
// 使用 Promise.all 来等待所有异步任务完成
await Promise.all(
Array.from({ length: 24 }, (_, i) => {
let formattedValue = (i + 1).toString().padStart(4, '0');
return this.requestData(formattedValue)
.then((PromiseResult) => {
if (PromiseResult.status === "success") {
this.images.push(PromiseResult.image);
this.positions.push(PromiseResult.position);
}
})
.catch((error) => {
console.error(`Error fetching data for value ${formattedValue}:`, error);
});
})
);
console.log("数据请求成功");
} catch (error) {
console.error("Error fetching data:", error);
}
this.endLoading();
}
在此修改后的代码中,使用了 Promise.all
方法来等待所有的异步任务完成。它接受一个 Promise 数组作为参数,并返回一个新的 Promise,该 Promise 在所有输入的 Promise 都已解析或有一个被拒绝时解析。这样就能够确保所有异步任务都完成后再执行后续的代码逻辑。