Asynchronous API request
suggest changeThe 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents