javascript - 另一个 promise 中的 promise

标签 javascript

我有一个 promise ,可以为每个部门获取其类别,我必须为每个类别添加另一个级别以获取其子类别

我添加了另一个 promise ,我只是想知道这是否是正确的方法,请告知。

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

关于javascript - 另一个 promise 中的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55994686/

相关文章:

Javascript 数学计算问题

javascript - 如何将数字 2.00 作为一个完整的字符串输出?

javascript - 忽略 Webpack/Babel 的 .d.ts 文件?

javascript - node-orm2 实例缺少保存方法

javascript - 从对象数组中,如何获取该对象值与变量匹配的对象值?

javascript - 检测文本框值的变化,其值在按钮单击时发生变化

javascript - 如何从开放的 Bootstrap 模式中获取 'id'?

javascript - 为什么不是 CDN 一切?

javascript - 为自定义元素加载 polyfill 的最佳方式是什么?

javascript - 您可以使用 Javascript 将日期/时间放入表单输入 onload 中吗?