【问题标题】:How to resolve nested promise arrays [duplicate]如何解决嵌套的承诺数组[重复]
【发布时间】:2021-01-08 18:42:36
【问题描述】:

我有一个 promise 数组,我想保持嵌套,因为它们是开始和结束位置坐标,所以这两组坐标应该在内部数组中保持在一起。

我正在尝试解决这些承诺,但我似乎无法让它发挥作用。我正在尝试映射外部数组以在内部数组上执行 Promise.all,但这并没有给我想要的结果。

这是我的代码:

const promises = idArr.map(route => route.map(id => (this.get(`places/${id}`))));
const places = promises.map(async route => (
    await Promise.all(route)
));

promises 在哪里:

[
  [ Promise { <pending> }, Promise { <pending> } ],
  [ Promise { <pending> }, Promise { <pending> } ],
  [ Promise { <pending> }, Promise { <pending> } ],
  [ Promise { <pending> }, Promise { <pending> } ],
  [ Promise { <pending> }, Promise { <pending> } ],
  [ Promise { <pending> }, Promise { <pending> } ],
  [ Promise { <pending> }, Promise { <pending> } ],
  [ Promise { <pending> }, Promise { <pending> } ],
  [ Promise { <pending> }, Promise { <pending> } ],
  [ Promise { <pending> }, Promise { <pending> } ]
]

这段代码给出了输出:

[
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> }
]

我尝试了映射 Promise.all 的不同组合,但在我看来,这应该是让它工作的方法,但我显然遗漏了一些东西。

【问题讨论】:

  • Promise.all(places) 是一个承诺,当所有内部承诺都被解决时。

标签: javascript promise


【解决方案1】:

Promise.all 缺少一层嵌套:

试试这个:

Promise.all(promises.map(x => Promise.all(x)).then(console.log);

【讨论】:

    【解决方案2】:

    如果你已经在一个数组中有 Promise 那么你应该这样做

    const promises = idArr.map(route => route.map(id => (this.get(`places/${id}`))));
    Promice.all(promises).then(result=> console.log(result))
    

    【讨论】:

      猜你喜欢
      • 2019-10-28
      • 2021-03-12
      • 2017-04-04
      • 1970-01-01
      • 2018-01-31
      • 2020-06-21
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      相关资源
      最近更新 更多