JAVASCRIPT
Making Multiple API Requests Concurrently with Promise.all
Efficiently fetch data from multiple API endpoints simultaneously using `Promise.all` in JavaScript, combining their results once all requests have successfully completed.
async function fetchMultipleEndpoints(urls) {
try {
const fetchPromises = urls.map(url =>
fetch(url).then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status} from ${url}`);
}
return response.json();
})
);
const results = await Promise.all(fetchPromises);
return results;
} catch (error) {
console.error('Error fetching multiple endpoints:', error);
throw error; // Re-throw to allow caller to handle
}
}
// Example Usage:
// const endpoints = [
// 'https://api.example.com/users/1',
// 'https://api.example.com/posts?userId=1',
// 'https://api.example.com/comments?postId=10'
// ];
//
// fetchMultipleEndpoints(endpoints)
// .then(([user, posts, comments]) => {
// console.log('User data:', user);
// console.log('User posts:', posts);
// console.log('Comments:', comments);
// })
// .catch(error => console.error('Failed to fetch all data:', error));
How it works: This snippet shows how to make several independent API calls in parallel using `Promise.all`. It takes an array of URLs, creates a `fetch` promise for each, and then waits for all promises to resolve. This significantly speeds up data loading compared to sequential requests, as all requests are initiated almost simultaneously. The results are returned as an array, maintaining the order of the input URLs. Error handling ensures that if any single request fails, the entire `Promise.all` operation rejects.