JAVASCRIPT
Handle Multiple Concurrent API Requests with Promise.allSettled
Learn to execute multiple asynchronous API requests in parallel and process all outcomes (fulfilled or rejected) using JavaScript's Promise.allSettled for robust data fetching.
async function fetchMultipleAPIs() {
const apiEndpoints = [
'https://jsonplaceholder.typicode.com/posts/1',
'https://jsonplaceholder.typicode.com/users/1',
'https://jsonplaceholder.typicode.com/comments/999999', // This one will likely fail (404)
'https://jsonplaceholder.typicode.com/todos/1'
];
const promises = apiEndpoints.map(url =>
fetch(url)
.then(response => {
if (!response.ok) {
// Instead of throwing immediately, return a rejected-like status
// This allows Promise.allSettled to correctly mark as 'rejected' later
return Promise.reject(new Error(`HTTP error! status: ${response.status} from ${url}`));
}
return response.json();
})
.catch(error => {
// Catch network errors or initial fetch failures
return Promise.reject(new Error(`Network or fetch error from ${url}: ${error.message}`));
})
);
console.log('Fetching multiple APIs concurrently...');
const results = await Promise.allSettled(promises);
console.log('All API requests have settled:');
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(` API ${index + 1} (${apiEndpoints[index]}) Succeeded:`, result.value);
} else {
console.error(` API ${index + 1} (${apiEndpoints[index]}) Failed:`, result.reason.message);
}
});
// You can also process data by filtering fulfilled results
const successfulData = results
.filter(result => result.status === 'fulfilled')
.map(result => result.value);
console.log('
Successfully fetched data:', successfulData);
}
fetchMultipleAPIs();
How it works: This snippet demonstrates using `Promise.allSettled` to execute multiple API requests concurrently. Unlike `Promise.all`, which short-circuits and rejects immediately if any promise in the iterable rejects, `Promise.allSettled` waits for all promises to either fulfill or reject. It then returns an array of objects, each describing the outcome of a promise ('fulfilled' with a `value` or 'rejected' with a `reason`). This is highly useful for scenarios where you want to process results from all requests, even if some of them fail, without halting the entire operation.