JAVASCRIPT

Batch Multiple Concurrent API Requests with Promise.all

Improve frontend performance and reduce network latency by batching multiple independent API requests concurrently using Promise.all in JavaScript.

async function fetchMultipleData(urls, options = {}) {
  try {
    const fetchPromises = urls.map(url => 
      fetch(url, options).then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status} for URL: ${url}`);
        }
        return response.json();
      })
    );
    
    const allResults = await Promise.all(fetchPromises);
    return allResults;
  } catch (error) {
    console.error('One or more API requests failed:', error);
    throw error; // Re-throw to allow further error handling up the call stack
  }
}

// Usage example:
const apiEndpoints = [
  'https://jsonplaceholder.typicode.com/todos/1',
  'https://jsonplaceholder.typicode.com/posts/1',
  'https://jsonplaceholder.typicode.com/users/1'
];

fetchMultipleData(apiEndpoints)
  .then(data => {
    console.log('All batched data fetched successfully:');
    console.log('Todo:', data[0]);
    console.log('Post:', data[1]);
    console.log('User:', data[2]);
  })
  .catch(error => console.error('Batch fetching failed:', error));

// Example with custom headers for all requests:
// const protectedEndpoints = [
//   'https://api.example.com/profile',
//   'https://api.example.com/settings'
// ];
// const authOptions = { headers: { 'Authorization': 'Bearer YOUR_TOKEN' } };
// fetchMultipleData(protectedEndpoints, authOptions)
//   .then(data => console.log('Protected data:', data))
//   .catch(error => console.error('Failed to fetch protected data:', error));
How it works: This snippet demonstrates how to efficiently fetch data from multiple API endpoints concurrently using `Promise.all` in JavaScript. Instead of sending requests sequentially, which can be slow, `Promise.all` allows all requests to be initiated almost simultaneously. It returns a single promise that resolves with an array of all the results when every individual request has successfully completed. If any of the promises reject (i.e., an API request fails), the `Promise.all` immediately rejects with the error of the first promise that failed, making error handling straightforward for the entire batch.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs