TypingKit
← Code

TypeScript: Fetch JSON with a timeout

Written for TypingKit · ~3 min

0 wpm 100% accuracy 100% real accuracy
interface User {↵
id: number;↵
name: string;↵
email?: string;↵
}↵
↵
async function getJson<T>(url: string, ms = 5000): Promise<T> {↵
const controller = new AbortController();↵
const timer = setTimeout(() => controller.abort(), ms);↵
try {↵
const res = await fetch(url, { signal: controller.signal });↵
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);↵
return (await res.json()) as T;↵
} finally {↵
clearTimeout(timer);↵
}↵
}↵
↵
export const user = await getJson<User>("/api/users/42");