在另一个诺言中的承诺

时间:2019-05-05 17:41:07

标签: javascript

我有一个承诺,每个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 });
  };

1 个答案:

答案 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 });
}