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:
- In the
fetchAllfunction, the promise is not returned fromurls.map, which causes thepromisesarray to containundefined. - The check
response.okis meaningless becauseresponseis an array of results, not a response object. - The
fetchAllfunction 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.