js call api example

// URL API сервиса
const apiUrl = 'https://api.example.com/data';

// Функция для установки таймаута
const fetchWithTimeout = (url, options = {}, timeout = 5000) => {
  return Promise.race([
    fetch(url, options),
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error('Таймаут запроса истек')), timeout)
    )
  ]);
};

// Вызов API с таймаутом
fetchWithTimeout(apiUrl, {}, 5000) // Таймаут 5000 мс = 5 секунд
  .then(response => {
    if (!response.ok) {
      throw new Error(`Ошибка HTTP: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    // Работаем с полученными данными
    console.log('Ответ от сервиса:', data);
  })
  .catch(error => {
    // Обработка ошибок, включая таймаут
    console.error('Ошибка:', error);
  });

Comments

Popular posts from this blog

xlam

crypto