JAVASCRIPT
Execute Multiple API Requests Concurrently with Promise.all
Learn to improve application performance by making several independent API calls in parallel using JavaScript's `Promise.all`, waiting for all to complete.
async function fetchMultipleResources(urls) {
try {
const fetchPromises = urls.map(async url => {
const response = await fetch(url);
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`HTTP error from ${url}! Status: ${response.status}, Details: ${errorData.message || 'Unknown error'}`);
}
return response.json();
});
// Wait for all promises to resolve
const results = await Promise.all(fetchPromises);
return results;
} catch (error) {
console.error("Error fetching multiple resources:", error);
throw error; // Re-throw to allow caller to handle
}
}
// Example usage:
async function loadDashboardData() {
const apiEndpoints = [
'https://api.example.com/users/1',
'https://api.example.com/products',
'https://api.example.com/orders/latest'
];
try {
const [user, products, latestOrder] = await fetchMultipleResources(apiEndpoints);
console.log('User data:', user);
console.log('Products list:', products);
console.log('Latest order:', latestOrder);
// Process all data once available
} catch (error) {
console.error('Failed to load dashboard data:', error.message);
}
}
// Call the example function
// loadDashboardData();
How it works: This snippet demonstrates how to efficiently fetch data from multiple API endpoints concurrently using `Promise.all`. By mapping an array of URLs to an array of `fetch` promises and passing them to `Promise.all`, the requests are initiated almost simultaneously. This significantly reduces the total loading time compared to making requests sequentially, as the application only waits for the slowest request to complete before processing all results.