我有一个承诺,每个department
都会获得其categories
,我必须为每个category
添加另一个级别才能获得其subcategories
。
我添加了另一个承诺,我只是想知道这是否是正确的方法,请告知。
componentDidMount = async () => {
const departments = await getDepartments();
const departmentsWithcategories = await Promise.all(
departments.map(async department => {
const categories = await getCategories(department.id);
categories.map(async category => {
const subCategories = await getSubCategories(category.id);
return { ...categories, subCategories };
});
return { ...department, categories };
}),
);
this.setState({ departmentsWithcategories });
};
更改前的功能:
componentDidMount = async () => {
const departments = await getDepartments();
const departmentsWithcategories = await Promise.all(
departments.map(async department => {
const categories = await getCategories(department.id);
return { ...department, categories };
}),
);
this.setState({ departmentsWithcategories });
};
答案 0 :(得分:2)
您还需要另一个Promise.all
来等待内部循环的结果。另外,您还忽略了它的返回值,可能是要散布单个category
而不是categories
数组。
async componentDidMount() {
const departments = await getDepartments();
const departmentsWithCategories = await Promise.all(departments.map(async department => {
const categories = await getCategories(department.id);
const categoriesWithSubcategories = Promise.all(categories.map(async category => {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^
const subCategories = await getSubCategories(category.id);
return { ...catgory, subCategories };
// ^^^^^^^
}));
return { ...department, categories: categoriesWithSubcategories };
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
}));
this.setState({ departmentsWithCategories });
}