// for (const item of response.rows) {
// item.groupName = await getGroupDetails(item.groupIds);
// }
for循环工作正常,它在移动到下一个项目之前等待每个getGroupDetails调用完成。这意味着在进入下一次迭代之前,item.groupName已正确设置。
此循环以顺序方式处理异步操作,确保每个getGroupDetails调用在继续之前完成
2.
await Promise.all(response.rows.map(async item => {
item.groupName = await getGroupDetails(item.groupIds);
}));
当使用带有异步函数的map时,map将返回一个promise数组,但它不会等待这些promise解析后再继续。因此,在继续之前,需要显式处理这些promise以确保它们都已解析。使用Promise.all
源代码:
async function getList() {
console.log('activeName.value', activeName.value);
loading.value = true;
queryParams.value.taskStatus = "";
queryParams.value.playType = "";
if (activeName.value == "1") {
// queryParams.value.taskStatus = 1;
}
// if (activeName.value == "3") {
// queryParams.value.playType = 2;
// }
const response = await getTaskList(queryParams.value);
total.value = response.total;
// 处理每项的分组名称
// for (const item of response.rows) {
// item.groupName = await getGroupDetails(item.groupIds);
// }
await Promise.all(response.rows.map(async item => {
item.groupName = await getGroupDetails(item.groupIds);
}));
TaskList.value = response.rows;
console.log('TaskList.value',TaskList.value);
loading.value = false
}
// 获取分组详情
async function getGroupDetails(groupIds) {
const ids = groupIds.split(',');
if (ids.length === 1) {
const response = await getGroup(ids[0]);
return response.data.groupName;
} else {
const groupNamePromises = ids.map(id =>
getGroup(id).then(response => response.data.groupName)
);
const groupNames = await Promise.all(groupNamePromises);
return groupNames.join(',');
}
}