【问题标题】:How to use `Array#map` within `Promise.all` in JavaScript如何在 JavaScript 的 Promise.all 中使用 Array#map
【发布时间】:2017-04-16 15:09:47
【问题描述】:

我正在尝试使用一组项目创建一个 Promise.all。因此,如果我这样创建它,它就可以正常工作

Promise.all([
  Query.getStuff(items[0]),
  Query.getStuff(items[1])
]).then(result => console.log(result))

如果我尝试像这样创建Promise.all,它不起作用

Promise.all([
    items.map(item => Query.getStuff(item))
]).then(result => console.log(result))

then 块在 Query.getStuff(item) 之前运行。我错过了什么?

【问题讨论】:

    标签: javascript promise


    【解决方案1】:

    你应该写

    Promise.all(items.map(...))
    

    而不是

    Promise.all([ items.map(...) ])
    

    Array#map 返回一个数组,这意味着您最初编写代码的方式实际上是将一个多维数组传递给Promise.all——就像在[ [promise1, promise2, ...] ] 中一样——而不是预期的一维版本[promise1, promise2, ...] .


    修改代码:

    Promise.all(
        items.map(item => Query.getStuff(item))
    ).then(result => console.log(result))
    

    【讨论】:

    • 什么是结果。是数组吗?
    • 是的@Gilboot 结果是一个与提供的数组顺序相同的数组。 const resultArray = await Promise.all(items.map(...))
    猜你喜欢
    • 2020-06-24
    • 2017-08-20
    • 2019-12-29
    • 2021-03-21
    • 2020-01-11
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多