javascript / intermediate
Snippet
Robust Result Handling with Promise.allSettled
Unlike Promise.all, which rejects immediately if any promise fails, Promise.allSettled waits for all operations to complete regardless of their outcome. This is essential for processing independent tasks where one failure shouldn't block others.
snippet.js
1
2
3
4
5
6
7
8
9
10
const urls = ['/api/user', '/api/settings'];const results = await Promise.allSettled(urls.map(url => fetch(url)));results.forEach((result, index) => {if (result.status === 'fulfilled') {console.log(`Success ${urls[index]}:`, result.value.status);} else {console.error(`Error ${urls[index]}:`, result.reason.message);}});
nodejs
Breakdown
1
await Promise.allSettled(...)
Waits for all promises to either resolve or reject.
2
result.status === 'fulfilled'
Checks if the specific promise succeeded.
3
result.reason
Contains the error object if the promise was rejected.