JAVASCRIPT
Making Concurrent API Requests with Promise.all
Optimize web application performance by making multiple independent API requests concurrently using JavaScript's `Promise.all`, fetching data faster.
async function fetchMultipleResources(urls, options = {}) {
try {
const fetchPromises = urls.map(url =>
fetch(url, options).then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status} for ${url}`);
}
return response.json();
})
);
const results = await Promise.all(fetchPromises);
return results;
} catch (error) {
console.error('One or more fetch requests failed:', error.message);
throw error;
}
}
// Example Usage:
// const apiEndpoints = [
// 'https://api.example.com/users',
// 'https://api.example.com/products',
// 'https://api.example.com/orders'
// ];
// fetchMultipleResources(apiEndpoints)
// .then(([users, products, orders]) => {
// console.log('All data fetched:');
// console.log('Users:', users);
// console.log('Products:', products);
// console.log('Orders:', orders);
// })
// .catch(err => console.error('Failed to fetch all resources:', err.message));
// Example with an invalid URL to demonstrate error handling:
// fetchMultipleResources(['https://api.example.com/users', 'https://api.example.com/nonexistent'])
// .then(data => console.log('Should not reach here:', data))
// .catch(err => console.error('Caught error for bad URL:', err.message));
How it works: This JavaScript snippet demonstrates how to fetch data from multiple API endpoints concurrently using `Promise.all`. It maps an array of URLs to an array of `fetch` promises, each with basic error checking. `Promise.all` then waits for all these promises to either resolve successfully, returning an array of results in the same order as the input URLs, or reject if any single request fails.