我有一个 promise ,可以为每个部门
获取其类别
,我必须为每个类别
添加另一个级别以获取其子类别
。
我添加了另一个 promise ,我只是想知道这是否是正确的方法,请告知。
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 });
};
最佳答案
您还需要另一个 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 });
}
关于javascript - 另一个 promise 中的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55994686/