Fetch JSON with timeout

Cancel a slow request using AbortSignal.timeout and check HTTP errors.

Original Pearto instructional example. Test it in your own environment and adapt it to your requirements.

News & updates

No news stories have been linked to this profile.

Search news coverage ↗

Sources & useful links

No publisher or independent source links have been added to this entry.

Suggest a source or correction ↗
async function getJSON(url, ms=5000) {
  const res = await fetch(url, {signal: AbortSignal.timeout(ms)});
  if (!res.ok) throw new Error('HTTP ' + res.status);
  return res.json();
}
// getJSON('/api/status').then(console.log).catch(console.error);