javascriptadvanced15 minutes

Fix Bug in Async Data Aggregation and Error Handling Function

Debug and fix a complex asynchronous JavaScript function designed to fetch and aggregate data from multiple APIs with error handling. The current implementation contains subtle bugs causing unhandled promise rejections and incorrect data aggregation.

Challenge prompt

You are given a function fetchAndAggregateData that asynchronously fetches data from three different APIs and combines the results into a single array. The function is supposed to handle errors gracefully by continuing to fetch data from other APIs even if one fails, but currently, it does not work as expected. Your task is to identify and fix all bugs so that the function properly fetches, aggregates, and handles errors without stopping prematurely or producing incorrect results.

Guidance

  • Check how promises are awaited and handled inside try/catch blocks.
  • Ensure error handling does not block fetching from remaining APIs.
  • Verify that all fetched data is combined correctly in the result.

Hints

  • Look for promise handling in parallel versus sequential execution.
  • Consider using Promise.allSettled to handle multiple async calls with independent error handling.
  • Watch out for cases where variable reassignment or overwriting causes data loss.

Starter code

async function fetchAndAggregateData() {
  const apiEndpoints = [
    'https://api.example.com/data1',
    'https://api.example.com/data2',
    'https://api.example.com/data3'
  ];
  let aggregatedData = [];
  for (const url of apiEndpoints) {
    try {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      const data = await response.json();
      aggregatedData = data;
    } catch (error) {
      console.error('Failed to fetch from:', url, error);
    }
  }
  return aggregatedData;
}

Expected output

An array containing combined data from all successful API fetches; errors logged but do not prevent aggregation of other successful results.

Core concepts

asynchronous programmingerror handlingpromisesAPI integrationdata aggregation

Challenge a Friend

Send this duel to someone else and see if they can solve it.