JAVASCRIPT

Executing Multiple API Requests Concurrently

Discover how to efficiently make several independent API calls in parallel using JavaScript's Promise.all to optimize data loading times in web applications.

async function fetchMultipleData() {
  try {
    // Define an array of promises for each independent API call
    const userPromise = fetch('https://api.example.com/users/1');
    const productsPromise = fetch('https://api.example.com/products?limit=5');
    const categoriesPromise = fetch('https://api.example.com/categories');

    // Wait for all promises to resolve concurrently
    const [userResponse, productsResponse, categoriesResponse] = await Promise.all([
      userPromise,
      productsPromise,
      categoriesPromise
    ]);

    // Check for response errors individually
    if (!userResponse.ok) throw new Error(`User API error! Status: ${userResponse.status}`);
    if (!productsResponse.ok) throw new Error(`Products API error! Status: ${productsResponse.status}`);
    if (!categoriesResponse.ok) throw new Error(`Categories API error! Status: ${categoriesResponse.status}`);

    // Parse JSON data concurrently
    const [userData, productsData, categoriesData] = await Promise.all([
      userResponse.json(),
      productsResponse.json(),
      categoriesResponse.json()
    ]);

    console.log('User Data:', userData);
    console.log('Products Data:', productsData);
    console.log('Categories Data:', categoriesData);
    return { user: userData, products: productsData, categories: categoriesData };
  } catch (error) {
    console.error('Error fetching data concurrently:', error);
    throw error; // Re-throw to allow callers to handle
  }
}

// Example usage:
// fetchMultipleData().then(data => console.log('All data fetched:', data)).catch(err => console.error('Failed to fetch all data:', err));
How it works: This snippet illustrates how to fetch data from multiple independent API endpoints concurrently. By placing each `fetch` call into an array of Promises and passing it to `Promise.all`, the requests are initiated almost simultaneously. The `await Promise.all` then waits for all promises to settle. This approach significantly reduces the total loading time compared to making each request sequentially, as it leverages parallel network operations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs