JAVASCRIPT
Execute Multiple API Requests in Parallel
Optimize data fetching by executing several independent API requests concurrently using `Promise.all` in JavaScript for faster loading times.
async function fetchMultipleResources(urls, token = null) {
try {
const fetchPromises = urls.map(url => {
const headers = { 'Content-Type': 'application/json' };
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
return fetch(url, { headers }).then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status} for URL: ${url}`);
}
return response.json();
});
});
const results = await Promise.all(fetchPromises);
console.log('All resources fetched successfully:', results);
return results;
} catch (error) {
console.error('Error fetching multiple resources:', error);
throw error;
}
}
// Example usage:
// const apiEndpoints = [
// 'https://api.example.com/users/1',
// 'https://api.example.com/products/category/electronics',
// 'https://api.example.com/notifications?status=unread'
// ];
// const authToken = 'YOUR_AUTH_TOKEN'; // Optional token
// fetchMultipleResources(apiEndpoints, authToken)
// .then(dataArray => {
// const [user, products, notifications] = dataArray;
// console.log('User data:', user);
// console.log('Products data:', products);
// console.log('Notifications data:', notifications);
// })
// .catch(error => console.error('Failed to fetch some resources:', error));
How it works: This snippet demonstrates how to make multiple API requests concurrently using `Promise.all`. It takes an array of URLs and maps each URL to a `fetch` call, creating an array of Promises. `Promise.all` then waits for all these Promises to resolve. This approach significantly reduces the total loading time compared to making requests sequentially, as all network operations run in parallel, making it ideal for dashboards or pages needing data from various endpoints.