0 day streak
javascript / intermediate
Snippet

Robust Async Control with Promise.allSettled

Unlike Promise.all, Promise.allSettled waits for all promises to finish (either fulfilled or rejected), allowing you to handle partial successes in a batch of operations.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
async function fetchData(urls) {
const promises = urls.map(url => fetch(url));
const results = await Promise.allSettled(promises);
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Success ${urls[index]}:`, result.value);
} else {
console.error(`Error ${urls[index]}:`, result.reason);
}
});
}
Breakdown
1
await Promise.allSettled(promises);
Waits for all async operations regardless of whether they succeed or fail.
2
result.status === 'fulfilled'
Inspects each result to determine the outcome of that specific operation.