gpt4 book ai didi

javascript - 将子类别添加到类别数组

转载 作者:行者123 更新时间:2023-12-02 23:52:13 24 4
gpt4 key购买 nike

我有一个Category对象,每个Category都有SubCategories。为每个Category加载其SubCategories的正确方法是什么?

const getCategories = async () => {
const { data: categories } = await axios.get(`api/Categories/GetCategories`);
return categories;
};

const getSubCategories = async catId => {
const { data: subCategories } = await axios.get(`../api/SubCategories/GetSubCategories?catId=${catId}`);
return subCategories;
};

最佳答案

这是一种简单但次优的方法,因为缺乏异步性。

const categories = getCategories().map(category => {
return {
category
, subCategory: getSubCategories(category.catId)
}
})

更好的方法是从 getSubCategories 中删除 await 并让它只返回 promise 。

const getSubCategories = async catId => axios.get(`../api/SubCategories/GetSubCategories?catId=${catId}`)

当您返回 Promise 时,它​​们可以异步运行。

const categories = getCategories()

如果您使用的是异步函数,您可以执行以下操作:

const subCategories = await Promise.all(categories.map(category => getSubCategories(category.catId))
const categoriesWithSub = zipWith(categories, subCategories, (category, subCategory) => ({category, subCategory}))

否则

Promise.all(categories.map(category => getSubCategories(category.catId))
.then(subCategories => {
const categoriesWithSub = zipWith(categories, subCategories, (category, subCategory) => ({category, subCategory}))
})

categoriesWithSub 是具有以下形状的对象数组。

[{
category: {} // however your original category object looked like.
, subCategory: [] // The array of subCategories for this category.
}]

关于javascript - 将子类别添加到类别数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55590707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com