Promise.allSettled()は2019年にES2020で追加された比較的新しいPromiseのメソッドです。複数のPromiseの実行結果をすべて取得できる便利な機能を持っています。

この記事では、Promise.allSettled()の基本的な使い方から実践的な使用例まで、分かりやすく解説していきます。

Promise.allSettled()とは

Promise.allSettled()は、複数のPromiseをまとめて実行し、各Promiseの結果(成功・失敗)を配列として取得できるメソッドです。

Promise.all()との大きな違いは、一つのPromiseが失敗しても処理が中断されず、すべてのPromiseの結果を取得できる点です。

基本的な使い方

const promise1 = Promise.resolve(1);
const promise2 = Promise.reject('エラー発生');
const promise3 = Promise.resolve(3);

Promise.allSettled([promise1, promise2, promise3])
  .then((results) => {
    console.log(results);
  });

// 出力結果:
// [
//   { status: "fulfilled", value: 1 },
//   { status: "rejected", reason: "エラー発生" },
//   { status: "fulfilled", value: 3 }
// ]

戻り値の形式

Promise.allSettled()の戻り値は、以下の形式のオブジェクトの配列です:

  • 成功した場合: `{ status: "fulfilled", value: 結果値 }`
  • 失敗した場合: `{ status: "rejected", reason: エラー内容 }`

実践的な使用例

APIリクエストを複数同時に行う場合の例:

const fetchUsers = async () => {
  const userIds = [1, 2, 3];
  const promises = userIds.map(id => 
    fetch(`https://api.example.com/users/${id}`)
      .then(res => res.json())
  );

  const results = await Promise.allSettled(promises);
  
  // 成功したリクエストの結果のみを取得
  const successfulResults = results
    .filter(result => result.status === "fulfilled")
    .map(result => result.value);
    
  return successfulResults;
};

Promise.all()との比較

Promise.all()は一つでもPromiseが失敗すると即座にエラーを返しますが、Promise.allSettled()はすべての処理が完了するまで待機します:

// Promise.all()の場合
Promise.all([promise1, promise2, promise3])
  .then(results => console.log('全て成功:', results))
  .catch(error => console.log('エラー発生:', error));
  // 一つでも失敗するとcatchに移行

// Promise.allSettled()の場合
Promise.allSettled([promise1, promise2, promise3])
  .then(results => {
    // 成功・失敗に関わらずすべての結果を取得
    console.log('すべての結果:', results);
  });

ブラウザ対応状況

Promise.allSettled()は比較的新しい機能のため、古いブラウザでは対応していない場合があります。その場合は、以下のようなポリフィルを使用することで対応できます:

if (Promise.allSettled === undefined) {
  Promise.allSettled = promises =>
    Promise.all(
      promises.map(p => p
        .then(value => ({
          status: "fulfilled",
          value,
        }))
        .catch(reason => ({
          status: "rejected",
          reason,
        }))
      )
    );
}

まとめ

Promise.allSettled()は、複数の非同期処理の結果をすべて取得したい場合に非常に便利なメソッドです。特に、一部の処理が失敗しても他の処理結果は必要な場合や、エラーハンドリングを柔軟に行いたい場合に活用できます。

API通信やファイル操作など、複数の非同期処理を扱う現代のWeb開発において、Promise.allSettled()は強力なツールとなります。