JAVASCRIPT
Efficient Concurrent API Calls Using Promise.all
Optimize data fetching by making multiple independent API requests concurrently using `Promise.all` in JavaScript, significantly reducing loading times for aggregated data.
async function fetchMultipleResources(urls, fetchOptions = {}) {
try {
const fetchPromises = urls.map(url =>
fetch(url, fetchOptions).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('Error fetching multiple resources:', error.message);
throw error; // Re-throw to allow caller to handle
}
}
// Example Usage:
const API_BASE = 'https://jsonplaceholder.typicode.com'; // A public test API
const resourceUrls = [
`${API_BASE}/posts/1`,
`${API_BASE}/users/2`,
`${API_BASE}/comments?postId=1`,
];
(async () => {
console.time('Fetch Multiple Resources');
try {
const [post, user, comments] = await fetchMultipleResources(resourceUrls);
console.log('Fetched Post:', post);
console.log('Fetched User:', user);
console.log('Fetched Comments (for Post 1):', comments);
} catch (error) {
console.error('Failed to fetch all resources:', error.message);
}
console.timeEnd('Fetch Multiple Resources');
// Demonstrate sequential fetching for comparison (slower)
console.time('Fetch Resources Sequentially');
try {
const postSequential = await (await fetch(resourceUrls[0])).json();
const userSequential = await (await fetch(resourceUrls[1])).json();
const commentsSequential = await (await fetch(resourceUrls[2])).json();
// console.log('Sequential Post:', postSequential);
// console.log('Sequential User:', userSequential);
// console.log('Sequential Comments:', commentsSequential);
} catch (error) {
console.error('Failed to fetch resources sequentially:', error.message);
}
console.timeEnd('Fetch Resources Sequentially');
})();
How it works: This JavaScript snippet demonstrates how to efficiently make multiple independent API calls concurrently using `Promise.all`. Instead of waiting for each request to complete sequentially, `Promise.all` allows you to initiate all requests almost simultaneously. It then waits for all promises to resolve (or for the first one to reject) and returns an array of their results in the same order as the input promises. This technique is invaluable for fetching aggregated data from different API endpoints, significantly reducing the overall loading time for your application compared to making requests one after another.