Sobes.tech
Middle

/** * È necessario scrivere una funzione che prenda in input un URL, * effettui una richiesta GET a quell'URL e restituisca i dati (json). * Per ottenere i dati, usare fetch. * È possibile usare solo l'API Promise. * Se si verifica un errore durante la richiesta, riprovare 5 volte. * Se alla fine non si riesce a ottenere le informazioni, restituire l'errore "URL specificato non accessibile". */ function get(url) { // codice qui } get(url) .then(res => console.log(res)) .catch(err => console.error(err))

sobes.tech AI

Risposta dell'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('Заданный URL недоступен'));
            }
        });
}

return tryFetch();

}

// Пример использования: // get('https://api.example.com/data') // .then(res => console.log(res)) // .catch(err => console.error(err));