JAVASCRIPT

Concurrent API Calls with Promise.all

Optimize web performance by executing multiple independent API requests concurrently using JavaScript's `Promise.all`, reducing overall loading times.

async function fetchMultipleResources(urls) {
  if (!Array.isArray(urls) || urls.length === 0) {
    console.warn('No URLs provided for concurrent fetching.');
    return [];
  }

  const fetchPromises = urls.map(url =>
    fetch(url)
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status} for ${url}`);
        }
        return response.json(); // Assuming JSON response
      })
      .catch(error => {
        console.error(`Error fetching ${url}:`, error);
        return null; // Return null or re-throw based on desired error handling
      })
  );

  try {
    const results = await Promise.all(fetchPromises);
    console.log('All requests completed.');
    // Filter out any failed requests (if they returned null)
    return results.filter(result => result !== null);
  } catch (overallError) {
    // This catch block will only execute if Promise.all rejects immediately,
    // which happens if any of the *individual* promises *rejects* without a catch.
    // Since we added .catch to individual promises, this block might not fire unless new errors are introduced.
    console.error('An unexpected error occurred during Promise.all:', overallError);
    return [];
  }
}

// Example Usage:
(async () => {
  const apiEndpoints = [
    'https://jsonplaceholder.typicode.com/posts/1',
    'https://jsonplaceholder.typicode.com/users/1',
    'https://jsonplaceholder.typicode.com/comments/1',
    'https://api.example.com/non-existent-resource' // Simulate a failing endpoint
  ];

  console.time('Concurrent Fetches');
  const allData = await fetchMultipleResources(apiEndpoints);
  console.timeEnd('Concurrent Fetches');

  if (allData.length > 0) {
    console.log('Fetched data:', allData);
    // Process allData: allData[0] is from posts/1, allData[1] from users/1, etc.
    console.log('Post:', allData[0]);
    console.log('User:', allData[1]);
  } else {
    console.log('No data fetched successfully.');
  }
})();
How it works: This JavaScript snippet demonstrates how to perform multiple independent API requests concurrently using `Promise.all`. Instead of fetching each resource sequentially, `Promise.all` takes an array of promises (each representing an API call) and waits for all of them to resolve. This significantly reduces the total time required to fetch multiple resources compared to making requests one after another. The snippet also includes individual error handling for each promise, ensuring that if one request fails, the others can still complete, and the overall operation doesn't halt prematurely.

Need help integrating this into your project?

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

Hire DigitalCodeLabs