Sobes.tech
Back to questions
Middle
2

/ ** * Необходимо написать функцию, которая на вход принимает url, * выполняет ходит по 1 этому урлу GET запрос и возвращает данные (json). * Для получения данных использовать fetch. * Можно использовать только Promise API * Если во время запроса произошла ошибка, то пробовать запросить ещё 5 раз. * Если в итоге информацию получить не удалось, вернуть ошибку "Заданный URL недоступен". * / function get(url) { // code here } get(url) .then(res => console.log(res)) .catch(err => console.error(err))

Companies where asked
Яндекс Сплит

Answer from AI

sobes.tech 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));