Asynchronous API request

suggest change

The Fetch API already returns a promise, so a modern GET helper does not need to wrap XMLHttpRequest manually:

async function getJson(url, { signal } = {}) {
  const response = await fetch(url, { signal });

  if (!response.ok) {
    throw new Error(`Request failed: ${response.status} ${response.statusText}`);
  }

  return response.json();
}

fetch() rejects for network failures and cancellation, but an HTTP error such as 404 still produces a fulfilled promise. Check response.ok or response.status before consuming the body.

Pass an AbortSignal when the caller needs cancellation:

const controller = new AbortController();

try {
  const data = await getJson('/api/items', { signal: controller.signal });
  console.log(data);
} catch (error) {
  if (error.name !== 'AbortError') {
    console.error(error);
  }
}

// Call controller.abort() when the request is no longer needed.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents