Tips
開発Tips(2025-11-02)
JavaScriptで非同期処理を扱う際に、Promise.allSettled()を使用すると、複数のPromiseの結果をまとめて処理し、エラー処理をより柔軟に行うことができます。エラー発生時にも他のPromiseの結果を取得したい場合に有効です。
JavaScript
JavaScriptで非同期処理を扱う際に、Promise.allSettled()を使用すると、複数のPromiseの結果をまとめて処理し、エラー処理をより柔軟に行うことができます。エラー発生時にも他のPromiseの結果を取得したい場合に有効です。
Promise.allSettled()の活用
Promise.all()は、いずれかのPromiseがrejectされると即座に全体がrejectされますが、Promise.allSettled()は、全てのPromiseがresolveまたはrejectされるまで待ち、それぞれの結果をオブジェクト配列として返します。
説明:
Promise.allSettled()は、複数の非同期処理の結果をまとめて処理する際に非常に便利です。特に、一部の処理が失敗しても、他の処理の結果を取得したい場合に役立ちます。戻り値のオブジェクト配列には、各Promiseの結果(statusとvalueまたはreason)が含まれています。
コード例:
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];
Promise.allSettled(promises)
.then((results) => results.forEach((result) => console.log(result.status)));
// Expected output:
// "fulfilled"
// "rejected"
Promise.allSettled(promises)
.then((results) => results.forEach((result) => {
if (result.status === "fulfilled") {
console.log("fulfilled: " + result.value);
} else {
console.log("rejected: " + result.reason);
}
}));
// Expected output:
// "fulfilled: 3"
// "rejected: foo"
注意点:
Promise.allSettled()は、全てのPromiseが完了するまで待機します。そのため、処理時間が長いPromiseが含まれている場合は、全体の処理時間も長くなる可能性があります。- 結果のオブジェクト配列の順番は、
Promise.allSettled()に渡したPromiseの順番に対応します。 Promise.allSettled()は、ES2020で導入された比較的新しい機能です。古いブラウザではサポートされていない場合があります。
おすすめポイント:
- エラーハンドリングをより柔軟に行いたい場合に最適です。
- 複数のAPIリクエストの結果をまとめて処理する際に便利です。
Promise.all()の代替として、より安全な処理を実現できます。