Fetch JSON with a timeout

Abort a fetch that takes too long and handle HTTP errors.

javascript intermediate #fetch#network#async
Abrir en el playground
js-fetch-timeout.js
async function getJSON(url, { timeout = 8000, ...options } = {}) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeout);
  try {
    const res = await fetch(url, { ...options, signal: controller.signal });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return await res.json();
  } finally {
    clearTimeout(timer);
  }
}

getJSON("https://api.github.com/repos/pallets/flask", { timeout: 5000 })
  .then((repo) => console.log(repo.full_name, "stars:", repo.stargazers_count))
  .catch((err) => console.error("failed:", err.message));