JavaScript 配列 .reduce と async/await 質問する

JavaScript 配列 .reduce と async/await 質問する

次のように、async/await を .reduce() に組み込む際にいくつか問題が発生しているようです。

const data = await bodies.reduce(async(accum, current, index) => {
  const methodName = methods[index]
  const method = this[methodName]
  if (methodName == 'foo') {
    current.cover = await this.store(current.cover, id)
    console.log(current)
    return {
      ...accum,
      ...current
    }
  }
  return {
    ...accum,
    ...method(current.data)
  }
}, {})
console.log(data)

オブジェクトはdataログに記録されます前に完了しますthis.store...

Promise.all非同期ループを利用できることは知っていますが、それは に適用されますか.reduce()?

ベストアンサー1

問題は、アキュムレータの値がプロミス、つまりasync functionsの戻り値であることです。連続評価(最後の反復を除くすべての反復を待機)を取得するには、以下を使用する必要があります。

const data = await array.reduce(async (accumP, current, index) => {
  const accum = await accumP;
}, Promise.resolve(…));

とはいえ、asyncawaitは一般的に配列反復メソッドの代わりに単純なループを使用するパフォーマンスが向上し、多くの場合、よりシンプルになります。

おすすめ記事