JavaScript の `Promise.all` 内で `Array#map` を使用する方法 質問する

JavaScript の `Promise.all` 内で `Array#map` を使用する方法 質問する

アイテムの配列を作成しようとしています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)。何が足りないのでしょうか?

ベストアンサー1

あなたは書くべきです

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

の代わりに

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

Array#mapは配列を返します。つまり、元のコードの記述方法では、実際Promise.allには[ [promise1, promise2, ...] ]、予想される 1 次元バージョンではなく、多次元配列が に渡されていました ( ) [promise1, promise2, ...]


改訂コード:

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

おすすめ記事