≡ Menu

Efficiently Fetching Data from Multiple APIs with Robust Error Handling 🚀

In today’s interconnected applications, it’s common to need data from various API endpoints.

Doing this efficiently and, more importantly, reliably is crucial.

I wanted to share a JavaScript async function I’ve been using that tackles this challenge head-on, ensuring concurrent data fetching and comprehensive error handling.

This function is a game-changer for scenarios where your application depends on data from several independent APIs and demands a robust way to manage potential failures.

async function fetchMultipleResources(urls) {
  try {
    const promises = urls.map(url => fetch(url));
    const responses = await Promise.all(promises);

    // Check if all responses are successful
    const allSuccess = responses.every(response => response.ok);

    if (!allSuccess) {
      const errorDetails = await Promise.all(responses.map(async response => {
        if (!response.ok) {
          return `${response.url}: ${response.status} - ${await response.text()}`;
        }
        return null;
      })).then(errors => errors.filter(error => error !== null).join(', '));
      throw new Error(`Failed to fetch all resources. Details: ${errorDetails}`);
    }

    // Parse the JSON data from all successful responses
    const data = await Promise.all(responses.map(response => response.json()));
    return data;
  } catch (error) {
    console.error('Error fetching resources:', error);
    throw error; // Re-throw the error for the calling function to handle
  }
}

How It Works and Why It’s Powerful

Let’s break down the key aspects that make this function so effective:

  • Concurrency with Promise.all(): The heart of its efficiency lies in Promise.all(). By mapping each URL to a Workspace promise and then awaiting them all simultaneously, we initiate and await multiple requests in parallel. This significantly boosts performance compared to fetching data sequentially, especially when dealing with many API calls.

  • Comprehensive Error Handling: This isn’t just about catching generic errors. The function specifically checks if all individual API requests were successful. If any fail, it goes the extra mile to gather detailed error information for each failure, including the URL, status code, and even the response body. This level of detail makes debugging much easier, as you immediately know what went wrong and where.

  • Data Integrity: By only proceeding with parsing the JSON data if allSuccess is true, we ensure that you only process data when all API calls are successful. This prevents unexpected issues that could arise from partial or incomplete data sets.

  • Ordered Results: A fantastic benefit is that the returned data array maintains the order of the input URLs. This makes it incredibly straightforward to associate the results with their original requests, eliminating any guesswork.

Example Usage

Here’s how you can put WorkspaceMultipleResources into action:

const apiEndpoints = [
  'https://jsonplaceholder.typicode.com/todos/1', // Example Todo API
  'https://jsonplaceholder.typicode.com/posts/1', // Example Post API
  'https://jsonplaceholder.typicode.com/users/1'  // Example User API
];

fetchMultipleResources(apiEndpoints)
  .then(results => {
    console.log('Successfully fetched data from all APIs:', results);

    // results will be an array containing the JSON data from each API in order
    console.log('Todo:', results[0]);
    console.log('Post:', results[1]);
    console.log('User:', results[2]);
  })
  .catch(error => {
    console.error('Failed to fetch data:', error);
  });

Note: The original example links were not publicly accessible, so I’ve substituted them with widely available JSON Placeholder API endpoints for demonstration purposes.


This WorkspaceMultipleResources function provides a robust and efficient solution for managing multiple API calls in your JavaScript applications. Have you encountered similar challenges in your projects, and what strategies have you found most effective?

{ 0 comments… add one }

Leave a Comment