Middle
/* * Write a function that takes a URL as input, * performs a GET request to this URL, * and returns the data (json). * Use fetch to get the data. * Only Promise API can be used. * If an error occurs during the request, try 5 more times. * If data cannot be obtained after all attempts, return the error "The specified URL is inaccessible". */ function get(url) { // code here } get(url) .then(res => console.log(res)) .catch(err => console.error(err))
sobes.tech AI
Answer from AI
javascript function get(url) { const maxRetries = 5; let attempts = 0;
function tryFetch() {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => {
if (attempts < maxRetries) {
attempts++;
return tryFetch();
} else {
return Promise.reject(new Error('The specified URL is not accessible'));
}
});
}
return tryFetch();
}
// Example usage: // get('https://api.example.com/data') // .then(res => console.log(res)) // .catch(err => console.error(err));