Javascript 一言堂
对于每个Javascript 一言堂,javascript,Javascript,对于每个部门其类别,我有一个承诺,我必须为每个类别添加另一个级别,以获得其子类别 我补充了另一个承诺,我只是想知道这是否是正确的方法,请建议 componentDidMount = async () => { const departments = await getDepartments(); const departmentsWithcategories = await Promise.all( departments.map(async departmen
部门
其类别
,我有一个承诺,我必须为每个类别
添加另一个级别,以获得其子类别
我补充了另一个承诺,我只是想知道这是否是正确的方法,请建议
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 });
}
您还需要另一个
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 });
}
好吧,行吗?这会给你带来什么问题吗?在没有实际错误的情况下,对与错可能有点主观。嗯,我想这更多的是用户体验方面的问题。您可以通过执行多个子查询来停止渲染,而不是对每个
部门
进行部分渲染。提前加载所有数据并等待链接承诺是否有附加值?平均渲染时间是多少?我无法回答这些问题,因为我没有使用数据,但我认为一旦你了解了用户行为,你就会对该做什么有一个更清晰的了解……好吧,它有效吗?这会给你带来什么问题吗?在没有实际错误的情况下,对与错可能有点主观。嗯,我想这更多的是用户体验方面的问题。您可以通过执行多个子查询来停止渲染,而不是对每个部门
进行部分渲染。提前加载所有数据并等待链接承诺是否有附加值?平均渲染时间是多少?我无法回答这些问题,因为我没有使用数据,但我认为,一旦您了解用户行为,您将更清楚地了解应该做什么。。。