foundation

Fetch API

Use promises, request and response objects, streams, AbortController, credentials, CORS behavior, and error handling.

fetch returns a promise for an HTTP response object; network failures reject, but HTTP error statuses still resolve. Good usage checks response.ok, handles JSON parsing failures, uses AbortController for cancellation or timeouts, understands credentials, and knows that CORS policy is enforced by the browser around the request.

					const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 8000);

try {
  const response = await fetch('/api/items', {
    signal: controller.signal,
    credentials: 'same-origin',
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return await response.json();
} finally {
  clearTimeout(timer);
}
				

Distinguish transport errors (reject) from application errors (4xx/5xx with ok false). CORS failures surface as network errors in the console without readable cross-origin bodies.

On interviews: aborting stale requests, differentiating transport and application errors, and explaining CORS symptoms.

Common pitfalls: assuming 404 rejects loses error handling. Forgetting credentials or headers can change auth and preflight behavior.

The trade-off is convenience versus control — pick the mechanism that matches your coupling and performance budget.

Checklist:

  • Check response.ok before parsing.
  • Handle JSON and abort errors.
  • Use AbortController for navigation and debounce.
  • Understand credentials and CORS interaction.