JAVASCRIPT
Execute Concurrent API Requests with Promise.all
Learn to simultaneously fetch data from multiple API endpoints using JavaScript's Promise.all, dramatically improving performance and reducing total load times for complex web applications.
async function fetchMultipleAPIData(urls) {
const fetchPromises = urls.map(url =>
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`API Error from ${url}: ${response.status} ${response.statusText}`);
}
return response.json();
})
);
try {
const results = await Promise.all(fetchPromises);
return results;
} catch (error) {
console.error('One or more API requests failed:', error);
throw error;
}
}
// Example usage:
/*
const apiEndpoints = [
'https://api.example.com/users/1',
'https://api.example.com/products/category/electronics',
'https://api.example.com/orders/recent'
];
fetchMultipleAPIData(apiEndpoints)
.then(([userData, productsData, ordersData]) => {
console.log('User Data:', userData);
console.log('Products Data:', productsData);
console.log('Orders Data:', ordersData);
})
.catch(error => console.error('Error fetching combined data:', error));
*/
How it works: This JavaScript snippet demonstrates how to make multiple API requests concurrently using `Promise.all`. By mapping an array of URLs to an array of `fetch` promises and then passing them to `Promise.all`, all requests are initiated simultaneously. The `await Promise.all` call then waits for all promises to resolve. This approach significantly reduces the total time required to fetch data from independent API endpoints compared to making them sequentially, enhancing application performance and responsiveness.