JAVASCRIPT
Execute Multiple Concurrent API Requests with Promise.all
Efficiently fetch data from multiple distinct API endpoints simultaneously using Promise.all in JavaScript, improving load times for complex dashboards or aggregated data views.
async function fetchMultipleAPIs() {
const urls = [
'https://api.example.com/data/users',
'https://api.example.com/data/products',
'https://api.example.com/data/orders'
];
try {
// Map each URL to a fetch promise
const requests = urls.map(url =>
fetch(url).then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status} from ${url}`);
}
return response.json();
})
);
// Wait for all promises to resolve
const [users, products, orders] = await Promise.all(requests);
console.log('Users Data:', users);
console.log('Products Data:', products);
console.log('Orders Data:', orders);
return { users, products, orders };
} catch (error) {
console.error('One or more API requests failed:', error);
// Handle individual or combined errors
throw error;
}
}
// Example Usage:
// fetchMultipleAPIs()
// .then(data => {
// console.log('All data fetched successfully:', data);
// // Update UI with all data
// })
// .catch(err => {
// console.error('Error fetching combined data:', err);
// });
How it works: This snippet demonstrates how to efficiently make multiple independent API requests concurrently using `Promise.all`. By mapping an array of API URLs to an array of `fetch` promises, `Promise.all` can then execute all these promises in parallel. The `await Promise.all(requests)` call will wait until all individual `fetch` operations have successfully resolved. If any of the promises in the array reject (e.g., due to a network error or non-OK HTTP status), `Promise.all` immediately rejects with the reason of the first promise that rejected. This pattern is ideal for loading various distinct data sets for a single view, such as a dashboard that requires user, product, and order information simultaneously.