JAVASCRIPT
Executing Parallel API Requests with Promise.all
Learn to make multiple API requests concurrently using JavaScript's `Promise.all`, significantly improving loading times for independent data fetches.
async function fetchMultipleResources(urls) {
const fetchPromises = urls.map(url =>
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status} for ${url}`);
}
return response.json();
})
.catch(error => {
console.error(`Error fetching ${url}:`, error);
return null; // Return null or re-throw based on desired error handling
})
);
try {
const results = await Promise.all(fetchPromises);
// Filter out nulls if some requests failed but you want to process others
// const successfulResults = results.filter(result => result !== null);
console.log('All parallel requests completed.');
return results;
} catch (error) {
// This catch block will only execute if Promise.all rejects,
// which happens if ANY promise in the array rejects AND is not caught internally.
// Since we catch errors in .map, Promise.all will always resolve, potentially with nulls.
console.error("An unexpected error occurred during Promise.all:", error);
throw error;
}
}
// Example Usage:
// const apiEndpoints = [
// 'https://api.example.com/users',
// 'https://api.example.com/products/featured',
// 'https://api.example.com/notifications'
// ];
// fetchMultipleResources(apiEndpoints)
// .then(allData => {
// console.log('Data from all endpoints:', allData);
// // allData will be an array corresponding to the order of apiEndpoints
// // Example: { users: allData[0], featuredProducts: allData[1], notifications: allData[2] }
// })
// .catch(error => console.error('Failed to fetch multiple resources:', error));
How it works: This JavaScript snippet demonstrates how to perform multiple API requests in parallel using `Promise.all`. It maps an array of URLs to an array of `fetch` promises, each with individual error handling. `Promise.all` then waits for all these promises to settle, returning an array of their results in the same order as the input URLs. This significantly improves efficiency compared to sequential fetching when data dependencies don't exist.