【问题标题】:Promise.all does only return resolved promises when used with async/awaitPromise.all 仅在与 async/await 一起使用时返回已解决的 Promise
【发布时间】:2020-07-18 21:15:54
【问题描述】:

我正在尝试使用 async/await 进行一些动态数据建模。 我有两个端点,第一个将返回一个对象数组。 数组中的这些实体具有从另一个端点获取的子实体。

所以我想要达到的结果类似于:

[{
  root: {
    id: 'root1'
  },
  children: [
    {
      id: 'child1'
    }, 
    {
      id: 'child2'
    }, 
  ]
}]

这就是我尝试解决这个问题的方法:

  let data = await rootLevel();
  let levelOneData = [];
  levelOneData = data.map((e) => {
    let rootNode = {};
    rootNode["root"] = e;
    return rootNode;
  });

  let levelTwoData = await Promise.all(
    levelOneData.map(async (e) => {
      let response = await fetch(
        `APIURL{e.parent.ID}`
      );
      let responseJSON = response.json();
      e["children"] = responseJSON;
      return e;
    })
  );

  const rootLevel = async () => {
    let response = await fetch(
      `APIURL`
    );
    return response.json();
  };

我的期望:

children: {Array(26)}

我得到了什么:

children: Promise {<resolved>: Array(26)}

我不知何故监督了我的 Promise.all 链中的某些东西,所以我只是得到解决 我的数据对象中的承诺,关于如何在其中获取纯数据的任何提示?或者如何变异 一组已解决的对实际数据的承诺?

【问题讨论】:

    标签: node.js async-await


    【解决方案1】:

    改变这个:

    let responseJSON = response.json();
    

    到这里:

    let responseJSON = await response.json();
    

    response.json() 是异步的并返回一个承诺。您只是将这个承诺放入您的结果中,而无需等待它。

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 2021-12-28
      • 2018-01-14
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      相关资源
      最近更新 更多