QuickSnip

Tag: async

Abort a fetch request if it takes longer than the given timeout.

export async function fetchWithTimeout(url, ms = 5000, options = {}) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), ms);
  try {
    const res = await fetch(url, { ...options, signal: controller.signal });
    return await res.json();
  } finally {
    clearTimeout(timer);

+2 more lines…

Updated Jul 17, 2026

Safe JSON fetch

TypeScript

Fetch JSON with explicit error handling for non-OK responses.

export async function getJSON<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) {
    throw new Error(`Request failed: ${res.status} ${res.statusText}`);
  }
  return (await res.json()) as T;
}
Updated Jul 17, 2026