JAVASCRIPT
Perform Multiple API Requests Concurrently with Promise.allSettled
Execute several independent API calls in parallel using JavaScript's Promise.allSettled, efficiently gathering all results and errors without stopping on the first rejection.
async function fetchMultipleEndpointsConcurrently(urls) {
if (!Array.isArray(urls) || urls.length === 0) {
console.warn('No URLs provided for concurrent fetching.');
return [];
}
const fetchPromises = urls.map(url =>
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status} from ${url}`);
}
return response.json();
})
.catch(error => {
console.error(`Error fetching ${url}:`, error);
throw error; // Re-throw to be caught by Promise.allSettled as 'rejected'
})
);
// Promise.allSettled waits for all promises to settle (either fulfilled or rejected)
// without short-circuiting on the first rejection, unlike Promise.all.
const results = await Promise.allSettled(fetchPromises);
// Process results:
const collectedData = [];
const errors = [];
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
collectedData.push(result.value);
} else {
// result.reason contains the error thrown by the catch block above
errors.push({ url: urls[index], error: result.reason });
}
});
return { data: collectedData, errors: errors };
}
// Example usage:
// const apiEndpoints = [
// 'https://jsonplaceholder.typicode.com/posts/1',
// 'https://jsonplaceholder.typicode.com/users/1',
// 'https://jsonplaceholder.typicode.com/comments/1',
// 'https://invalid-url.typicode.com/data' // Example of a failing request
// ];
// fetchMultipleEndpointsConcurrently(apiEndpoints)
// .then(({ data, errors }) => {
// console.log('Successfully fetched data:', data);
// if (errors.length > 0) {
// console.error('Errors encountered:', errors);
// }
// })
// .catch(overallError => {
// // This catch block would only be hit if Promise.allSettled itself throws, which it doesn't.
// // All individual errors are caught within the map and reported in the 'errors' array.
// console.error('An unexpected overall error occurred:', overallError);
// });
How it works: This JavaScript snippet demonstrates how to make multiple API requests concurrently using `Promise.allSettled`. Unlike `Promise.all` which fails if any promise rejects, `Promise.allSettled` waits for all promises to complete (either fulfill or reject) and returns an array of objects describing the outcome of each promise. This pattern is highly useful for API integrations where you need to fetch data from several independent endpoints in parallel, ensuring that all available data is processed and errors are reported without halting the entire operation.