Vanilla JavaScript Data Fetching
Fetch and render remote data with vanilla JavaScript using async/await, AbortController for cancellation, loading state management, and error handling with.
Code
async function fetchData(url, { signal, retries = 3 } = {}) {
for (let i = 0; i < retries; i++) {
try {
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
if (err.name === 'AbortError') throw err;
if (i === retries - 1) throw err;
await new Promise((r) => setTimeout(r, 2 ** i * 1000));
}
}
}How it works
Vanilla JavaScript Data Fetching comes down to the function fetchData.
Iteration happens inside for (let i = 0; i < retries; i++) — everything outside it runs once. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Invalid states are rejected up front: it throws Error instead of continuing with bad data.
Watch out for
fetchexist only in browsers — a Node runtime has no shims for them out of the box.- The guard
!res.okshort-circuits the flow with an earlythrowwhen its condition holds.
Applying it
Entry signature: async function fetchData(url, { signal, retries = 3 } = {})
Statements that matter
await new Promise((r) => setTimeout(r, 2 ** i * 1000));
return await res.json();
if (!res.ok) throw new Error(`HTTP ${res.status}`);
Interactive Tools for This Topic
FAQ
- What happens on invalid input?
- The code refuses to continue: `Error` is thrown while the state is still recoverable.
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `fetchData` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.