user3378165
user3378165

Reputation: 6896

Promise within another promise

I have a promise that gets for each department its categories, I have to add another level- for each category to get its subcategories.

I added another promise, I'm just wondering if this is the right way to do it, please advise.

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

Function before change:

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

Upvotes: 0

Views: 56

Answers (1)

Bergi
Bergi

Reputation: 664538

You will also need another Promise.all to wait for the results of the inner loops. Also you were ignoring its return value, and probably you meant to spread the individual category not the categories array.

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

Upvotes: 2

Related Questions