Sobes.tech
Middle

fetchAll(['url1', 'url2'], (results) => { console.log('Data for all links', results); }); function fetchAll(urls) { const promises = urls.map((url) => { fetch(url).then((res) => res.json()) }) const data = Promise.all(promises).then((response) => { if (!response.ok) { throw new Error('error') } return response }) console.log(data) }

sobes.tech AI

Answer from AI

The provided code has several errors and shortcomings:

  1. In the fetchAll function, the promise is not returned from urls.map, which causes the promises array to contain undefined.
  2. The check response.ok is meaningless because response is an array of results, not a response object.
  3. The fetchAll function takes two parameters, but the second parameter (callback) is not used.

Here's a corrected version of the function using promises and a callback:

function fetchAll(urls, callback) {
  const promises = urls.map(url => 
    fetch(url).then(res => {
      if (!res.ok) {
        throw new Error(`Loading error ${url}: ${res.status}`);
      }
      return res.json();
    })
  );

  Promise.all(promises)
    .then(results => callback(results))
    .catch(error => console.error('Error loading data:', error));
}

fetchAll(['url1', 'url2'], (results) => {
  console.log('Data from all links', results);
});

This approach guarantees that all requests are executed in parallel, and after all are successfully completed, the callback is called with the array of results.