JAVASCRIPT
Client-Side Utility for Batching Parallel API Requests
Optimize client-side performance by executing multiple independent API requests in parallel and efficiently collecting all their results using a single utility function and Promise.all().
async function batchParallelRequests(requestConfigs) {
const fetchPromises = requestConfigs.map(config => {
const { url, method = 'GET', body, headers } = config;
const options = {
method,
headers: { 'Content-Type': 'application/json', ...headers }
};
if (body && (method === 'POST' || method === 'PUT')) {
options.body = JSON.stringify(body);
}
return fetch(url, options)
.then(response => {
if (!response.ok) {
return response.json().then(errorData => {
throw new Error(`HTTP ${response.status}: ${JSON.stringify(errorData)}`);
}).catch(() => {
throw new Error(`HTTP ${response.status} for ${url}`);
});
}
return response.json();
})
.catch(error => ({
url,
status: 'failed',
error: error.message || 'Network error'
})); // Gracefully handle individual request failures
});
// Wait for all promises to settle (either fulfilled or rejected)
const results = await Promise.allSettled(fetchPromises);
// Process results to separate successful and failed ones
const formattedResults = results.map((result, index) => {
if (result.status === 'fulfilled') {
return { url: requestConfigs[index].url, status: 'success', data: result.value };
} else {
// For Promise.allSettled, result.reason is the error thrown by the promise
return { url: requestConfigs[index].url, status: 'failed', error: result.reason.error || result.reason.message || 'Unknown error' };
}
});
return formattedResults;
}
// Example usage:
// const requests = [
// { url: 'https://jsonplaceholder.typicode.com/todos/1' },
// { url: 'https://jsonplaceholder.typicode.com/users/1' },
// { url: 'https://jsonplaceholder.typicode.com/non-existent-endpoint' } // Simulate a failed request
// ];
// batchParallelRequests(requests)
// .then(allResults => {
// console.log('Batch results:', allResults);
// // You can then filter or process allResults
// })
// .catch(error => console.error('Batch error:', error));
How it works: This client-side JavaScript utility enables sending multiple independent API requests in parallel and collecting their results efficiently. It accepts an array of request configuration objects, maps them to `fetch` promises, and then uses `Promise.allSettled` to wait for all promises to complete, regardless of success or failure. This ensures that a single failed request doesn't block the entire batch, allowing the application to process partial data. The results are formatted to clearly indicate the status and data (or error) for each individual request.