JAVASCRIPT
Optimize API Calls by Batching Requests
Improve application performance and reduce network overhead by batching multiple related API requests into a single optimized call using Promise.all in JavaScript.
async function fetchBatchedData(ids) {
const BASE_URL = 'https://api.example.com/items/';
// Map IDs to an array of Promise objects, each representing an API call
const fetchPromises = ids.map(id =>
fetch(`${BASE_URL}${id}`).then(response => {
if (!response.ok) {
throw new Error(`Failed to fetch item ${id}: ${response.statusText}`);
}
return response.json();
})
);
try {
// Use Promise.all to await all promises concurrently
const results = await Promise.all(fetchPromises);
console.log('All data fetched successfully:', results);
return results;
} catch (error) {
console.error('Error fetching batched data:', error);
throw error; // Re-throw to allow caller to handle
}
}
// Example Usage:
const itemIdsToFetch = [1, 2, 3, 4, 5];
fetchBatchedData(itemIdsToFetch)
.then(data => {
console.log('Processed batched data:', data);
})
.catch(err => {
console.log('Failed to process some data.');
});
// If your API supports a single endpoint for multiple IDs (true batching):
async function fetchTrueBatchedData(ids) {
const API_ENDPOINT = 'https://api.example.com/batch-items';
try {
const response = await fetch(API_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: ids })
});
if (!response.ok) {
throw new Error(`Batch fetch failed: ${response.statusText}`);
}
const result = await response.json();
console.log('True batched data fetched:', result);
return result;
} catch (error) {
console.error('Error in true batch fetch:', error);
throw error;
}
}
// Example Usage for true batching:
const anotherSetOfIds = [6, 7, 8];
fetchTrueBatchedData(anotherSetOfIds)
.then(data => console.log('Processed true batched data:', data))
.catch(err => console.log('Failed to process true batched data.'));
How it works: This snippet illustrates two ways to batch API requests for improved performance. The `fetchBatchedData` function uses `Promise.all` to concurrently send multiple individual GET requests for a list of `ids`. This reduces the total time spent waiting for responses compared to sequential fetching. The `fetchTrueBatchedData` function demonstrates an ideal scenario where the API itself supports a single endpoint (e.g., a POST request) to fetch multiple resources, significantly reducing network overhead. Batching is crucial for applications that need to display data from many related API calls, minimizing latency and improving responsiveness.