1. ホーム
  2. javascript

[解決済み] JavaScriptの配列.reduceとasync/await

2022-10-04 13:02:16

質問

.reduce()にasync/awaitを組み込むと、以下のような問題があるようです。

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() ?

どのように解決するのですか?

問題は、アキュムレータの値が約束事であることです。 async function s. 順次評価(と、最後の反復以外は全く待たされない)を得るには、以下のようにする必要があります。

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

とはいえ async / await 私は一般的に 配列の反復処理ではなく、単純なループを使うことをお勧めします。 その方がパフォーマンスも良く、シンプルであることが多いからです。