JAVASCRIPT
Execute Concurrent API Calls with `Promise.allSettled`
Optimize data loading by making multiple API requests simultaneously using `Promise.allSettled`, handling individual success or failure gracefully without blocking others.
async function fetchMultipleApiEndpoints(urls) {
const fetchPromises = urls.map(async (url) => {
try {
const response = await fetch(url);
if (!response.ok) {
// Treat non-OK responses as rejections with specific error
throw new Error(`HTTP error! Status: ${response.status} for ${url}`);
}
return await response.json();
} catch (error) {
// Catch network errors or parsing errors
throw new Error(`Failed to fetch ${url}: ${error.message}`);
}
});
// Use Promise.allSettled to wait for all promises to settle (either fulfilled or rejected)
const results = await Promise.allSettled(fetchPromises);
const successfulResponses = [];
const failedRequests = [];
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
successfulResponses.push({
url: urls[index],
data: result.value
});
} else {
failedRequests.push({
url: urls[index],
reason: result.reason.message || 'Unknown error'
});
}
});
return { successfulResponses, failedRequests };
}
// Usage example:
// const apiUrls = [
// 'https://api.example.com/users/1',
// 'https://api.example.com/posts/101',
// 'https://api.example.com/comments/invalid-id', // This one will fail
// 'https://api.example.com/settings'
// ];
// fetchMultipleApiEndpoints(apiUrls)
// .then(({ successfulResponses, failedRequests }) => {
// console.log('Successful Fetches:', successfulResponses);
// console.log('Failed Fetches:', failedRequests);
// // Process your data here
// })
// .catch(error => {
// console.error('Unexpected error in Promise.allSettled:', error);
// });
How it works: This JavaScript snippet demonstrates how to efficiently make multiple API requests concurrently and process their results using `Promise.allSettled`. Unlike `Promise.all`, which fails entirely if any of the promises reject, `Promise.allSettled` waits for all promises to either fulfill or reject, returning an array of objects describing the outcome of each. This approach is ideal when you need to fetch data from several independent endpoints and want to present partial results or handle individual failures gracefully without crashing the entire operation.