全Promiseの成功・失敗を問わず全結果を返す
// ── 全Promiseの結果を(成否に関わらず)全て受け取る ──────
// Promise.all は1つ失敗すると全部止まるが、allSettled は続ける
const results = await Promise.allSettled([
fetch('/api/users'), // 成功とする
fetch('/api/posts'), // エラーが起きても
fetch('/api/comments'), // こちらも処理される
]);
// 全件完了後に結果を確認
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
// 成功: result.value に結果が入っている
console.log('成功 ' + index + ':', result.value);
} else {
// 失敗: result.reason にエラーが入っている
console.error('失敗 ' + index + ':', result.reason);
}
});
// ── Promise.all との使い分け ──────────────────────────
// Promise.all → 全部成功が必要(1つ失敗で中断)
// Promise.allSettled → 部分的成功でOK(全結果を集めたい)エラーが起きても他のリクエスト結果を使いたい場合に有用。Promise.allより失敗に寛容。