JAVASCRIPT

Batching Multiple Independent API Requests with Promise.all

Improve web application performance by concurrently fetching data from multiple independent API endpoints using JavaScript's `Promise.all`, reducing overall loading times.

async function fetchBatchData() {
  const USERS_API = 'https://api.example.com/users';
  const PRODUCTS_API = 'https://api.example.com/products';
  const ORDERS_API = 'https://api.example.com/orders';

  try {
    // Create an array of Promises for each API call
    const [usersResponse, productsResponse, ordersResponse] = await Promise.all([
      fetch(USERS_API),
      fetch(PRODUCTS_API),
      fetch(ORDERS_API)
    ]);

    // Check if all responses are OK
    if (!usersResponse.ok || !productsResponse.ok || !ordersResponse.ok) {
      throw new Error('One or more API requests failed.');
    }

    // Parse JSON from each response concurrently
    const [users, products, orders] = await Promise.all([
      usersResponse.json(),
      productsResponse.json(),
      ordersResponse.json()
    ]);

    console.log('Users:', users);
    console.log('Products:', products);
    console.log('Orders:', orders);

    return { users, products, orders };

  } catch (error) {
    console.error('Error fetching batch data:', error);
    throw error;
  }
}

// Example Usage:
fetchBatchData()
  .then(data => {
    console.log('All data fetched successfully:', data);
  })
  .catch(error => {
    console.error('Failed to fetch some data:', error);
  });

// Note: If you need to fetch data sequentially or if one request depends on another,
// avoid Promise.all and use await for each request in order.
How it works: This JavaScript snippet demonstrates how to efficiently fetch data from multiple *independent* API endpoints concurrently using `Promise.all`. Instead of waiting for each request to complete before starting the next, `Promise.all` allows all requests to be initiated almost simultaneously. This significantly reduces the overall time required to fetch all necessary data, improving application performance, especially when dealing with dashboards or pages that aggregate information from various sources.

Need help integrating this into your project?

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

Hire DigitalCodeLabs