簡體   English   中英

在另一個諾言中的承諾

[英]Promise within another promise

我保證每個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 });
  };

您還需要另一個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 });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM