原来代码
this.jobs.forEach((job) => {
let jobGroup: JobGroup = {
title: 'Job--' + job.jobName,
tasks: []
};
/*todo 因为是异步请求导致顺序有问题*/
taskApi.getCoordinatesByJobId(job.id).then((data) => {
this.tasks = data.data;
console.info("hCom.ets---Tasks for jobid " + job.id + ": " + JSON.stringify(this.tasks));
// jobGroup.tasks= [];// 初始化 jobGroup的tasks 为一个空数组
this.tasks.forEach((task) => {
//创建taskShow对象完成
let taskShow: TaskShow = {
key: task.taskId,
name: 'Task' + task.taskId,
icon:$r('app.media.taskIcon')
};
jobGroup.tasks.push(taskShow);
});
this.jobGroups.push(jobGroup);
}).catch((error) => {
console.log('Error fetching tasks for jobid ' + job.id + ': ', error);
});
});
套一层Promise.all()
let promises = this.jobs.map(job => {
return taskApi.getCoordinatesByJobId(job.id).then(data => {
this.tasks = data.data;
console.info("Tasks for jobid " + job.id + ": " + JSON.stringify(this.tasks));
let jobGroup: JobGroup = {
title: 'Job--' + job.jobName,
tasks: []
};
this.tasks.forEach(task => {
let taskShow: TaskShow = {
key: task.taskId,
name: 'Task' + task.taskId,
icon: $r('app.media.taskIcon')
};
jobGroup.tasks.push(taskShow);
});
return jobGroup;
}).catch(error => {
console.log('Error fetching tasks for jobid ' + job.id + ': ', error);
return null;
});
});
Promise.all(promises).then(jobGroups => {
// jobGroups 数组现在包含了所有按顺序处理好的 jobGroup 对象
this.jobGroups = jobGroups.filter(group => group !== null); // 过滤掉可能的错误结果(如果需要)
});