JAVASCRIPT
Efficiently Batching Multiple Independent API Requests
Learn how to use `Promise.all` to concurrently fetch data from multiple API endpoints, significantly improving load times and user experience for dashboard-like interfaces.
async function fetchMultipleApiEndpoints(urls, requestOptions = {}) {
try {
const fetchPromises = urls.map(url =>
fetch(url, requestOptions).then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status} for ${url}`);
}
return response.json();
})
);
// Promise.all waits for all promises to resolve
const results = await Promise.all(fetchPromises);
return results;
} catch (error) {
console.error('Error fetching multiple endpoints:', error);
throw error;
}
}
// Example Usage:
// const apiEndpoints = [
// 'https://api.example.com/users',
// 'https://api.example.com/products',
// 'https://api.example.com/orders?status=pending'
// ];
// const commonHeaders = {
// headers: {
// 'Authorization': 'Bearer YOUR_AUTH_TOKEN',
// 'Content-Type': 'application/json'
// }
// };
// fetchMultipleApiEndpoints(apiEndpoints, commonHeaders)
// .then(([usersData, productsData, ordersData]) => {
// console.log('Users:', usersData);
// console.log('Products:', productsData);
// console.log('Orders:', ordersData);
// // Process all data together
// })
// .catch(error => console.error('Failed to get all data:', error.message));
How it works: This JavaScript snippet demonstrates how to efficiently fetch data from multiple independent API endpoints concurrently using `Promise.all`. Instead of making requests sequentially, `Promise.all` allows all network requests to start almost simultaneously. The function returns a single promise that resolves with an array of results from all successful fetches, or rejects if any single fetch fails, making it ideal for loading dashboard data or aggregating information from various sources.